httpclient的maven依赖
在pom.xml中加入下面内容:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
接受响应数据HttpClientResult:
package com.bjsxt.entity;
import java.io.Serializable;
public class HttpClientResult implements Serializable {
private static final long serialVersionUID = 2168152194164783950L;
private int code;
private String content;
public HttpClientResult() {
}
public HttpClientResult(int code) {
this.code = code;
}
public HttpClientResult(String content) {
this.content = content;
}
public HttpClientResult(int code, String content) {
this.code = code;
this.content = content;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "HttpClientResult [code=" + code + ", content=" + content + "]";
}
}
工具类HttpClientUtils :
package com.bjsxt.util;
import com.bjsxt.entity.HttpClientResult;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.Map.Entry;
public class HttpClientUtils {
private static final String ENCODING = "UTF-8";
private static final int CONNECT_TIMEOUT = 6000;
private static final int SOCKET_TIMEOUT = 6000;
public static HttpClientResult doGet(String url) throws Exception {
return doGet(url, null, null);
}
public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, null, params);
}
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
packageHeader(headers, httpGet);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpGet);
} finally {
release(httpResponse, httpClient);
}
}
public static HttpClientResult doPost(String url) throws Exception {
return doPost(url, null, null);
}
public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
return doPost(url, null, params);
}
public static HttpClientResult doPostBody(String url,String requestBody) throws Exception{
System.out.println(requestBody);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
ByteArrayEntity entity = null;
try {
entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));
entity.setContentType("application/json");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("向服务器承保接口发起http请求,封装请求body时出现异常", e);
}
httpPost.setEntity(entity);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
packageHeader(headers, httpPost);
packageParam(params, httpPost);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
release(httpResponse, httpClient);
}
}
public static HttpClientResult doPut(String url) throws Exception {
return doPut(url);
}
public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
packageParam(params, httpPut);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
release(httpResponse, httpClient);
}
}
public static HttpClientResult doDelete(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
release(httpResponse, httpClient);
}
}
public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
if (params == null) {
params = new HashMap<String, String>();
}
params.put("_method", "delete");
return doPost(url, params);
}
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
}
public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
if (params != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
}
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
httpResponse = httpClient.execute(httpMethod);
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}