现象:
公司项目从springboot1.x升级到2.x后,使用httpclient4.5包模拟表单请求,调用其他服务接口,结果返回501。
使用postman或restTemplate调用返回就正常,java程序调用就不行。java代码如下:
省略其他代码……
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//头信息
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
//模拟post表单提交,使用UrlEncodedFormEntity请求体
List<NameValuePair> data = new ArrayList<NameValuePair>();
for(Map.Entry<String,Object> entry:requestParams.entrySet()){
data.add(new BasicNameValuePair(entry.getKey(), entry.getValue()+""));
}
//设置UrlEncodedFormEntity请求体
httpPost.setEntity(new UrlEncodedFormEntity(data,"UTF-8"));
//请求
HttpResponse response = client.execute(httpPost);
省略其他代码……
解决办法:
把请求体改成StringEntity,用json串去请求post接口,代码如下:
省略其他代码……
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//头信息
httpPut.setHeader("Content-Type","application/json;charset=utf-8");
//设置StringEntity请求体
httpPost.setEntity(httpPut.setEntity(new StringEntity(ObjectMapperM.getInstanceOf().getMapper().writeValueAsString(requestParams),"UTF-8")););
//请求
HttpResponse response = client.execute(httpPost);
省略其他代码……