背景介绍
近期在开发公司项目并与第三方系统进行数据对接时,需要将采集的数据发送至对方服务器。依据对方提供的技术文档配置参数后,调用 httpclient.execute(method) 发起请求,但始终返回 502 状态码。由于初次尝试使用 HttpClient 提交 JSON 数据,曾反复排查自身代码逻辑。后来在技术论坛看到关于 URL 中包含空格的讨论,才猛然发现对方提供的 PDF 文档中实际包含了空格字符,而自己此前因天真地忽略这一细节,误以为是文档错误所致。
接下来直接切入正题。
在使用 PostMethod 发起请求时,需特别注意以下两点:
第一,若运行环境为公司内部服务器,务必正确配置代理服务器地址及端口号。
第二,若目标 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);
代码逻辑较为直观,此处不再赘述。此次经历再次提醒我们,看似简单的文档细节往往隐藏着关键陷阱。
补充场景:利用 HttpClient 与 PostMethod 同时上传文件和请求参数
为避免冗长叙述,直接展示核心代码片段。
//HttpClient发起请求
public static String sendUrlFile(String url, String jsonstr) {
String result = "";
try {
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod(url);
FilePart filePart = new FilePart("file", new File("/root/桌面/文档/记录.txt"));
filePart.setCharSet("utf-8");
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
//Part数组装需要传第的参数和文件等
Part[] parts = {new StringPart("username",jsonstr , "utf-8"),filePart};
MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
post.setRequestEntity(entity);
int code = httpclient.executeMethod(post);
//拿到响应结果
result = new String(post.getResponseBody(), "UTF-8");
//可释放连接
post.releaseConnection();
return result;
} catch (HttpException h) {
LOGGER.error("cause HttpException:" + h.getMessage());
} catch (Exception i) {
LOGGER.error("发送请求错误: url cause IOException:" + i.getMessage());
}
return "";
}
//接收请求服务器端 参数需要和发送端一致
@ResponseBody
@RequestMapping(value = “/login”)
public JsonResult revice(@RequestParam(“file”) MultipartFile file,@RequestParam(“username”)String username) throws IOException{
InputStream in = file.getInputStream();
OutputStream out = new FileOutputStream("/root/桌面/ok.txt");
byte[] bs = new byte[1024];
int len;
while(-1 != (len = (in.read(bs)))){
out.write(bs);
}
JsonResult json = new JsonResult();
System.out.println();
json.setResult(“ok”);
return json;
}
以上内容为个人实践经验总结,旨在提供参考。如有疏漏或未尽之处,欢迎指正。