Apache HttpClient是Apache提供的一个开源组件,使用HttpClient可以很方便地进行Http请求的调用。自4.1版本开始,HttpClient的API发生了较大的改变,很多方法的调用方式已经和3.x版本不同。本文使用的是当前最新的4.5.3版本。
首先在pom文件中引入httpcomponents依赖包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
本文展示的是POST请求。
import java.io.IOException; import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
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.util.EntityUtils; /**
* @author
*
* @date 2017年5月18日 上午9:17:30
*
* @Description
*/
public class HttpPostUtils {
/**
*
* @param uri
* the request address
* @param json
* the request data that must be a JSON string
* @param connectTimeout
* the timeout in milliseconds until a connection is established
* @param connectionRequestTimeout
* the timeout in milliseconds used when requesting a connection
* from the connection manager
* @param socketTimeout
* the socket timeout in milliseconds, which is the timeout for
* waiting for data or, put differently, a maximum period
* inactivity between two consecutive data packets
* @return null when method parameter is null, "", " "
* @throws IOException
* if HTTP connection can not opened or closed successfully
* @throws ParseException
* if response data can not be parsed successfully
*/
public String postJson(String uri, String json, int connectTimeout, int connectionRequestTimeout, int socketTimeout)
throws IOException, ParseException {
if (StringUtils.isAnyBlank(uri, json)) {
return null;
} CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(uri);
// Create request data
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
// Set request body
post.setEntity(entity); RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build();
post.setConfig(config);
// Response content
String responseContent = null;
CloseableHttpResponse response = null;
try {
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
responseContent = EntityUtils.toString(response.getEntity(), Consts.UTF_8.name());
}
} finally {
if (ObjectUtils.anyNotNull(response)) {
response.close();
}
if (ObjectUtils.anyNotNull(client)) {
client.close();
}
}
return responseContent;
}
}