- 需要引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
- 使用案例
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
public class UseHttpclientDemo {
public static void main(String[] args) {
String postResultData = postResult();
if (postResultData == null) {
System.out.println("{\"errno\":-1,\"errmsg\":\"fail\",\"message\":\"调用接口获取数据失败\"}");
return;
}
System.out.println(postResultData);
String getResultData = getResult();
if (getResultData == null) {
System.out.println("{\"errno\":-1,\"errmsg\":\"fail\",\"message\":\"调用接口获取数据失败\"}");
return;
}
System.out.println(getResultData);
}
public static String postResult() {
//超时时间
/**
* RequestConfig.DEFAULT == 一直请求
* RequestConfig.DEFAULT == RequestConfig.custom()
* .setConnectTimeout(-1).setConnectionRequestTimeout(-1).setSocketTimeout(-1)
* .build();
*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(3000) //连接主机超时时间
.setConnectionRequestTimeout(4000) //请求超时时间
.setSocketTimeout(5000) //数据读取超时时间
.build();
//请求体
StringEntity requestBody = new StringEntity("{\"invoke_info\":{\"pos_1\":[{}],\"pos_2\":[{}],\"pos_3\":[{}]}}", ContentType.APPLICATION_JSON);
//http客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
//post请求
HttpPost postRequest = new HttpPost();
postRequest.setConfig(requestConfig);
postRequest.setURI(URI.create("https://ug.baidu.com/mcp/pc/pcsearch")); //请求路径
postRequest.addHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); //请求头
postRequest.addHeader("xxx","xxx");
postRequest.addHeader("xxx","xxx");
postRequest.setEntity(requestBody); //请求体
String result = null;
try {
//发送请求
CloseableHttpResponse response = httpClient.execute(postRequest);
if (response == null || response.getStatusLine() == null || response.getStatusLine().getStatusCode() !=200) {
return null;
}
/**
* response.getHeaders("xxx"); //响应头
* response.getEntity().getContent(); //响应体(获取文件数据)
* EntityUtils.toString(response.getEntity(), Charset.defaultCharset()); //响应体(获取json数据)
*/
//响应内容
String responseBody = EntityUtils.toString(response.getEntity(), Charset.defaultCharset()); //响应体(获取json数据)
result = responseBody;
} catch (ClientProtocolException e) {
//接口调用异常或接口数据传输异常
System.out.println("接口调用异常:"+e);
System.out.println(ExceptionUtils.getStackTrace(e));
} catch (IOException e) {
//接口数据传输异常
System.out.println("接口调用异常:"+e);
System.out.println(ExceptionUtils.getStackTrace(e));
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
//关闭httpclient失败
System.out.println("关闭httpclient失败:");
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
}
return result;
}
public static String getResult() {
//超时时间
/**
* RequestConfig.DEFAULT == 一直请求
* RequestConfig.DEFAULT == RequestConfig.custom()
* .setConnectTimeout(-1).setConnectionRequestTimeout(-1).setSocketTimeout(-1)
* .build();
*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(3000) //连接主机超时时间
.setConnectionRequestTimeout(4000) //请求超时时间
.setSocketTimeout(5000) //数据读取超时时间
.build();
//http客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
//post请求
HttpGet getRequest = new HttpGet();
getRequest.setConfig(requestConfig);
getRequest.setURI(URI.create("https://dict.youdao.com/login/acc/query/accountinfo?withCredentials=true&caKu=3")); //请求路径+入参
getRequest.addHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); //请求头
getRequest.addHeader("xxx","xxx");
getRequest.addHeader("xxx","xxx");
String result = null;
try {
//发送请求
CloseableHttpResponse response = httpClient.execute(getRequest);
if (response == null || response.getStatusLine() == null || response.getStatusLine().getStatusCode() !=200) {
return null;
}
/**
* response.getHeaders("xxx"); //响应头
* response.getEntity().getContent(); //响应体(获取文件数据)
* EntityUtils.toString(response.getEntity(), Charset.defaultCharset()); //响应体(获取json数据)
*/
//响应内容
String responseBody = EntityUtils.toString(response.getEntity(), Charset.defaultCharset()); //响应体(获取json数据)
result = responseBody;
} catch (ClientProtocolException e) {
//接口调用异常或接口数据传输异常
System.out.println("接口调用异常:"+e);
System.out.println(ExceptionUtils.getStackTrace(e));
} catch (IOException e) {
//接口数据传输异常
System.out.println("接口调用异常:"+e);
System.out.println(ExceptionUtils.getStackTrace(e));
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
//关闭httpclient失败
System.out.println("关闭httpclient失败:");
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
}
return result;
}
}
标签:java,System,接口,apache,println,import,out,response,httpclient
From: https://www.cnblogs.com/gaoguanghui/p/18688749