通过HttpClien 调用API的时候服务端返回缺少参数
以下是原来的第三的服务商提供的方法,使用后一直提示缺少返回值,
private static String sendHttpRequest(String url, Map<String, String> bodyMap)
throws Exception {
System.out.println("请求地址:" + url);
System.out.println("发送参数:" + bodyMap.toString());
HttpClient client = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(url);
postRequest.addHeader("Content-Type", "application/json;charset=UTF-8");
postRequest.setHeader("Accept", "aplication/json");
List<NameValuePair> nvps = new ArrayList<>();
for (String key : bodyMap.keySet()) {
nvps.add(new BasicNameValuePair(key, bodyMap.get(key)));
}
log.info("post请求:{}", nvps);
postRequest.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
int retry = 3;
HttpResponse execute = null;
while (retry-- > 0) {
try {
execute = client.execute(postRequest);
break;
} catch (Exception e) {
Thread.sleep(5000);
}
}
if (execute == null) {
throw new Exception("接口请求失败");
}
String resp = EntityUtils.toString(execute.getEntity());
System.out.println("接口返回:" + resp);
return resp;
}
最后差了很多资料才知道使用HttpClient发送post请求时会遇到服务端收不到参数的情况,查找了一下原因是因为大部分使用Httpclient模拟post请求时都会把参数放在Entity里面,示例如下:
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(),"utf-8");
上面的这种设置参数的方式通过request.getParameter(“key”)的方式获取不到参数,所以如果想通过request.getParameter(“key”)获取参数,则需要修改HttpClient模拟post请求时设置参数的方式,示例如下:
private static HttpPost postForm(String url, Map<String, String> params) {
URIBuilder builder;
HttpPost httpost = null;
try {
builder = new URIBuilder(url);
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
Set<String> keySet = params.keySet();
for(String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
builder.setCharset(Consts.UTF_8);
builder.setParameters(nvps);
httpost = new HttpPost(builder.build());
} catch (URISyntaxException e) {
e.printStackTrace();
}
return httpost;
}
API返回的数据中带有斜杠
终于解决了上面的问题.结果发现返回的数据是这样的…
{“online”:true,“connect_time”:“2023-04-18
:54:35”,“status”:“SUCCESS”,“cid”:“20221005912”}
还是在返回的时候使用fastjson中的 JSON.parse() 方法即可处理完.