1.准备jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
2.设置请求头和请求体代码片段:
public static String sendG7Post(String url,String params) {
HttpClient httpClient = null;
HttpPost postMethod = null;
HttpResponse response = null;
String reponseContent = null;
try {
httpClient = HttpClients.createDefault();
postMethod = new HttpPost(url);//传入URL地址
//设置请求头
postMethod.addHeader("Content-type", "application/json; charset=utf-8");
postMethod.addHeader("X-Authorization", "AAAA");//设置请求头
//传入请求参数
postMethod.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
response = httpClient.execute(postMethod);//获取响应
int statusCode = response.getStatusLine().getStatusCode();
log.info("HTTP Status Code:" + statusCode);
if (statusCode != HttpStatus.SC_OK) {
log.info("HTTP请求未成功!HTTP Status Code:" + response.getStatusLine());
}
HttpEntity httpEntity = response.getEntity();
reponseContent = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);//释放资源
log.info("响应内容:" + reponseContent);
return reponseContent;
} catch (Exception e) {
e.printStackTrace();
}
return reponseContent;
}
public static String sendHqtPost(String url,String params,String authorization) {
HttpClient httpClient = null;
HttpPost postMethod = null;
HttpResponse response = null;
String reponseContent = null;
try {
httpClient = HttpClients.createDefault();
postMethod = new HttpPost(url);//传入URL地址
//设置请求头
postMethod.addHeader("Content-type", "application/json; charset=utf-8");
postMethod.addHeader("Authorization", authorization);//设置请求头
//传入请求参数
postMethod.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
response = httpClient.execute(postMethod);//获取响应
int statusCode = response.getStatusLine().getStatusCode();
log.info("HTTP Status Code:" + statusCode);
if (statusCode != HttpStatus.SC_OK) {
log.info("HTTP请求未成功!HTTP Status Code:" + response.getStatusLine());
}
HttpEntity httpEntity = response.getEntity();
reponseContent = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);//释放资源
log.info("响应内容:" + reponseContent);
return reponseContent;
} catch (Exception e) {
e.printStackTrace();
}
return reponseContent;
}
3.根据第三方要求传入需要设置的请求头内容