java HttpClient传输json格式的参数实例讲解
最近的一个接口项目,传的参数要求是json,需要特殊处理一下。
重点是这两句话:
httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
se.setContentType(CONTENT_TYPE_TEXT_JSON);
这两句话的作用与jmeter的设置header信息类似
packagecom.base;
importjava.io.UnsupportedEncodingException;
importorg.apache.http.HttpEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.entity.StringEntity;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.impl.conn.PoolingClientConnectionManager;
importorg.apache.http.util.EntityUtils;
/**
*@authorQiaoJiafei
*@version创建时间:2015年11月4日下午1:55:45
*类说明
*/
publicclassHttpGetByJson{
publicstaticvoidmain(Stringargs[])throwsException{
finalStringCONTENT_TYPE_TEXT_JSON="text/json";
DefaultHttpClientclient=newDefaultHttpClient(
newPoolingClientConnectionManager());
Stringurl="http://172.16.30.226:8091/svc/authentication/register";
Stringjs="{\"userName\":\"18600363833\",\"validateChar\":\"706923\",\"randomChar\":\"706923\",\"password\":\"123456\",\"confirmPwd\":\"123456\",\"recommendMobile\":\"\",\"idCard\":\"320601197608285792\",\"realName\":\"阙岩\",\"verifyCode\"}";
HttpPosthttpPost=newHttpPost(url);
httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
StringEntityse=newStringEntity(js);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
httpPost.setEntity(se);
CloseableHttpResponseresponse2=null;
response2=client.execute(httpPost);
HttpEntityentity2=null;
entity2=response2.getEntity();
Strings2=EntityUtils.toString(entity2,"UTF-8");
System.out.println(s2);
}
}
补充:HttpClient以json形式的参数调用http接口并对返回的json数据进行处理(可以带文件)
1、参数的url就是被调用的地址,map是你要传的参数。参数转成json我使用的是gson方式转换的。
主要使用的jar包有httpclient-4.5.3.jar、httpcore-4.4.6.jar、commons-codec-1.9.jar、gson-2.2.4.jar和commons-logging-1.2.jar。
如果发送的post请求想传送文件,需添加httpmime-4.5.3.jar包,并设置如下代码:
HttpEntitymultipartEntityBuilder=MultipartEntityBuilder.create().addBinaryBody("file",newFile("D:\\workspace\\programm\\WebContent\\programm\\1991.zip")).build();
第一个参数表示请求字段名,第二个参数就是文件。
还想添加参数则
HttpEntitymultipartEntityBuilder=MultipartEntityBuilder.create().addTextBody("name","张三").addBinaryBody("file",newFile("D:\\workspace\\programm\\WebContent\\programm\\1991.zip")).build();
httpPost.setEntity(multipartEntityBuilder);
importjava.io.IOException;
importjava.util.Map;
importorg.apache.http.HttpEntity;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.entity.StringEntity;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.util.EntityUtils;
importcom.google.gson.Gson;
publicclassHttpClientUtil{
privatefinalstaticStringCONTENT_TYPE_TEXT_JSON="text/json";
publicstaticStringpostRequest(Stringurl,Mapparam)throwsClientProtocolException,IOException{
CloseableHttpClientclient=HttpClients.createDefault();
HttpPosthttpPost=newHttpPost(url);
httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
Gsongson=newGson();
Stringparameter=gson.toJson(param);
StringEntityse=newStringEntity(parameter);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
httpPost.setEntity(se);
CloseableHttpResponseresponse=client.execute(httpPost);
HttpEntityentity=response.getEntity();
Stringresult=EntityUtils.toString(entity,"UTF-8");
returnresult;
}
}
2、返回的结果也可以使用gson转换成对象进行下一步操作。
importcom.google.gson.Gson;
publicclassGsonUtil{
publicstaticTjsonToObject(StringjsonData,Classtype){
Gsongson=newGson();
Tresult=gson.fromJson(jsonData,type);
returnresult;
}
publicstaticvoidmain(String[]args){
Stringjson="{'id':'1','name':'zhang','address':'Hubei'}";
jsonToObject(json,Person.class);
Personperson=jsonToObject(json,Person.class);
System.out.println(person);
}
}
建立要转成的对象的类。
importjava.util.Date;
publicclassPerson{
privateintid;
privateStringname;
privateintage;
privateStringaddress;publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
publicStringgetAddress(){
returnaddress;
}
publicvoidsetAddress(Stringaddress){
this.address=address;
}
@Override
publicStringtoString(){
return"Person[id="+id+",name="+name+",age="+age+",address="+address+"]";
}
}
3、发送以键值对形式的参数的post请求
packagecom.avatarmind.httpclient;
importjava.util.ArrayList;
importjava.util.List;
importorg.apache.http.HttpEntity;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
publicclassHttpClient3{
publicstaticvoidmain(String[]args)throwsException{
CloseableHttpClientclient=HttpClients.createDefault();
Stringurl="http://yuntuapi.amap.com/datamanage/table/create";
HttpPosthttpPost=newHttpPost(url);
//参数形式为key=value&key=value
Listformparams=newArrayList();
formparams.add(newBasicNameValuePair("key","060212638b94290e3dd0648c15753b64"));
formparams.add(newBasicNameValuePair("name","火狐"));
//加utf-8进行编码
UrlEncodedFormEntityuefEntity=newUrlEncodedFormEntity(formparams,"UTF-8");
httpPost.setEntity(uefEntity);
CloseableHttpResponseresponse=client.execute(httpPost);
HttpEntityentity=response.getEntity();
Stringresult=EntityUtils.toString(entity,"UTF-8");
System.out.println(result);
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。