当使用HttpClient来发送post请求,并且入参是json字符串
比如 json = { "name" : "zhangsan", "age" : 24};
在java中可以这样写 String postbody= "{" + "\"name\":\""zhangsan"\"" + "\"age\":\""24"\""+ "}";
当使用StringEntity来添加消息体:
StringEntity reqentity = new StringEntity( postbody,"utf-8");
httpPost.setEntity(reqentity);
在java中必须要对json数据用"\"进行转义,否则将在传入的入参将获取不到这个参数和内容,
当有个json文件的内容为{ "name" : "zhangsan", "age" : 24};
这个时候我们把这个json文件做为入参的话,先要把这json文件读取,读取出来就是
String json = { "name" : "zhangsan", "age" : 24};
读取出来的json字符串是没有转义的,这个时候用StringEntity来不行的,需要用到UrlEncodedFormEntity() 来设置消息体会自动转义不会对入参造成错误;
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("postbody", json ));
// 加utf-8进行编码
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(uefEntity);