在协议传输的json格式数据一般都会是用“=”“&”作为分隔:例如:“ type=online&mode=5&plate_num= 京 A12345&plate_color= 蓝 色
&plate_val=true&confidence=25&car_logo= 丰 田 &car_color= 白 色 &vehicle_type= 轿 车”
这里提供了解析的方法:
public static MapformData2Dic(String formData ) { Map result = new HashMap<>(); if(formData== null || formData.trim().length() == 0) { return result; } final String[] items = formData.split("&"); Arrays.stream(items).forEach(item ->{ final String[] keyAndVal = item.split("="); if( keyAndVal.length == 2) { try{ final String key = URLDecoder.decode( keyAndVal[0],"utf8"); final String val = URLDecoder.decode( keyAndVal[1],"utf8"); result.put(key,val); }catch (UnsupportedEncodingException e) {} } }); return result; }
调用:
//获得查询字符串(get)
// String queryString = exchange.getRequestURI().getQuery();
//获得表单提交数据(post)
String postString = IOUtils.toString(httpExchange.getRequestBody(), Charset.forName("UTF-8"));
Map postInfo = formData2Dic(postString);
for (String key : postInfo.keySet()) {
Object value = postInfo.get(key);
System.out.println(key + ":" + value);
}
测试结果:



