版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36719449/article/details/82227427
故事前要
今天,在做公司的一个项目,需要和第三方公司进行对接,需要将我们采集到的数据发送给第三方公司,按照对方提供的文档,传递好参数后,httpclient.execute(method)请求后,得到的状态码 ,一直是502,犹豫第一次使用HttpClient post json数据,一直怀疑是自己的代码问题,最后不知在哪个技术论坛看到 ,有人问url请求中有空格怎么办,突然发现对方提供的pdf文档中 竟然包含空格,而我天真的无视掉了 以为是文档的问题。
算了…… 不多BB了….
PostMethod请求注意两点:
1、如果使用的是公司的服务器,设置好代理和端口。
2、如果url中有空格,需要使用%20 进行转义。
贴一下我的代码 ,给不会还没用过不会PostMethod请求的萌新们…
HttpClient httpClient = new HttpClient();
String host = (String) BaseConfig.get("host");
String port = (String) BaseConfig.get("port");
httpClient.getHostConfiguration().setProxy(host, Integer.valueOf(port));
PostMethod postMethod = new PostMethod(applyurl);
JSONObject jsonObject = new JSONObject();
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");
String toJson = jsonObject.toString();
RequestEntity se = new StringRequestEntity (toJson ,"application/json" ,"UTF-8");
postMethod.setRequestEntity(se);
postMethod.setRequestHeader("Content-Type","application/json");
//默认的重试策略
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);//设置超时时间
int httpStatus = hc.executeMethod(postMethod);
String str=postMethod.getResponseBodyAsString();
T.console("str-------:"+str);
代码很简单,就不过多解释了,最后感谢这个坑爹的文档,又让我学到了一招。