}
这里的参数根据自己的实际情况来设定,这种调用一般都是外部调用,考虑到双方协调性问题最好并发量不要设置特别大,调用不要特别频繁,最好每天控制调用数量。
public static String sendPostForCaice(HttpClient httpClient, String url, Map
String resp = "";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8");
if (params != null && params.size() > 0) {
StringEntity se = new StringEntity(JsonUtil.toJson(params), encoding);
httpPost.setEntity(se);
}
CloseableHttpResponse response = null;
try {
response = (CloseableHttpResponse) httpClient.execute(httpPost);
if(response!=null && 200 == response.getStatusLine().getStatusCode()){
resp = EntityUtils.toString(response.getEntity(), encoding);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return resp;
}
该方法用于发送post请求,JsonUtil.toJson(params)作用是把map转换为json类型的String字符串,最后发送请求,得到返回结果
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8"); 这个头部信息是根据双方约定来设置。
public static String sendPut(HttpClient httpClient, String url,String authorization,Map
HttpPut httpPut = new HttpPut(url);
//header存放 LPCC_TOKEN
httpPut.addHeader(Const.AUTHORIZATION,"jwt "+authorization);
httpPut.addHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8");
if (params != null && params.size() > 0) {
StringEntity se = new StringEntity(JsonUtil.toJson(params), encoding);
httpPut.setEntity(se);
}
HttpResponse httpResponse = null;
String res = null;
try {
httpResponse = httpClient.execute(httpPut);
if(httpResponse!=null && 200 == httpResponse.getStatusLine().getStatusCode()){
res = EntityUtils.toString(httpResponse.getEntity(), encoding);
}
} catch (ClientProtocolException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return res;
}
该方法是发送put请求,代码基本和post请求没什么区别。
这里再说一下如果要发送get请求,基本代码也是这样,只是get请求不需要设置请求参数的StringEntity,参数都追加到url后面。