java 利用HttpClient PostMethod提交json数据操作
故事前要
今天,在做公司的一个项目,需要和第三方公司进行对接,需要将我们采集到的数据发送给第三方公司,按照对方提供的文档,传递好参数后,httpclient.execute(method)请求后,得到的状态码,一直是502,犹豫第一次使用HttpClientpostjson数据,一直怀疑是自己的代码问题,最后不知在哪个技术论坛看到,有人问url请求中有空格怎么办,突然发现对方提供的pdf文档中竟然包含空格,而我天真的无视掉了以为是文档的问题。
算了……不多BB了….
PostMethod请求注意两点:
1、如果使用的是公司的服务器,设置好代理和端口。
2、如果url中有空格,需要使用%20进行转义。
贴一下我的代码,给不会还没用过不会PostMethod请求的萌新们…
HttpClienthttpClient=newHttpClient();
Stringhost=(String)BaseConfig.get("host");
Stringport=(String)BaseConfig.get("port");
httpClient.getHostConfiguration().setProxy(host,Integer.valueOf(port));
PostMethodpostMethod=newPostMethod(applyurl);
JSONObjectjsonObject=newJSONObject();
jsonObject.put("name",user.getName());
jsonObject.put("phone",user.getPhone());
jsonObject.put("provinceCode",user.getProvinceCode());
jsonObject.put("cityCode",user.getCityCode());
jsonObject.put("buyModelCode",user.getBuyModelCode());
jsonObject.put("dealerCode",user.getDealerCode());
jsonObject.put("url","http:xxx");
StringtoJson=jsonObject.toString();
RequestEntityse=newStringRequestEntity(toJson,"application/json","UTF-8");
postMethod.setRequestEntity(se);
postMethod.setRequestHeader("Content-Type","application/json");
//默认的重试策略
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,newDefaultHttpMethodRetryHandler());
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,5000);//设置超时时间
inthttpStatus=hc.executeMethod(postMethod);
Stringstr=postMethod.getResponseBodyAsString();
T.console("str-------:"+str);
代码很简单,就不过多解释了,最后感谢这个坑爹的文档,又让我学到了一招。
补充:利用HttpClient&PostMethod上传文件和请求参数
我就废话不多说了,大家还是直接看代码吧~
//HttpClient发起请求
publicstaticStringsendUrlFile(Stringurl,Stringjsonstr){
Stringresult="";
try{
HttpClienthttpclient=newHttpClient();
PostMethodpost=newPostMethod(url);
FilePartfilePart=newFilePart("file",newFile("/root/桌面/文档/记录.txt"));
filePart.setCharSet("utf-8");
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
//Part数组装需要传第的参数和文件等
Part[]parts={newStringPart("username",jsonstr,"utf-8"),filePart};
MultipartRequestEntityentity=newMultipartRequestEntity(parts,post.getParams());
post.setRequestEntity(entity);
intcode=httpclient.executeMethod(post);
//拿到响应结果
result=newString(post.getResponseBody(),"UTF-8");
//可释放连接
post.releaseConnection();
returnresult;
}catch(HttpExceptionh){
LOGGER.error("causeHttpException:"+h.getMessage());
}catch(Exceptioni){
LOGGER.error("发送请求错误:urlcauseIOException:"+i.getMessage());
}
return"";
}
//接收请求服务器端参数需要和发送端一致
@ResponseBody
@RequestMapping(value=“/login”)
publicJsonResultrevice(@RequestParam(“file”)MultipartFilefile,@RequestParam(“username”)Stringusername)throwsIOException{
InputStreamin=file.getInputStream();
OutputStreamout=newFileOutputStream("/root/桌面/ok.txt");
byte[]bs=newbyte[1024];
intlen;
while(-1!=(len=(in.read(bs)))){
out.write(bs);
}
JsonResultjson=newJsonResult();
System.out.println();
json.setResult(“ok”);
returnjson;
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。