com.github.jerryxia.devutil.http.HttpHelper Maven / Gradle / Ivy
/**
*
*/
package com.github.jerryxia.devutil.http;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.methods.HttpUriRequest;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Administrator
*
*/
public final class HttpHelper {
private static final Logger log = LoggerFactory.getLogger(HttpHelper.class);
private static final int DEFAULT_TIMEOUT = 20 * 1000;
public static final RequestConfig DEFAULT_REQUEST_CONFIG = defaultRequestConfigBuilder().build();
/**
* 简单Get请求,等价于:
* HttpGet httpGet = buildSimpleGet(uri, params, DEFAULT_REQUEST_CONFIG);
*
return simpleExecuteRequest(httpPost);
*
* @param uri 指定的Uri
* @param params 可以为null
* @return
* @throws URISyntaxException
*/
public static String simpleGet(String uri, Map params) throws URISyntaxException {
HttpGet httpGet = buildSimpleGet(uri, params, DEFAULT_REQUEST_CONFIG);
String responseString = simpleExecuteRequest(httpGet);
return responseString;
}
/**
* 表单提交请求,等价于:
* HttpPost httpPost = buildSimpleFormPost(uri, params, DEFAULT_REQUEST_CONFIG);
*
return simpleExecuteRequest(httpPost);
*
* @param uri 指定的Uri
* @param params 可以为null
* @return
*/
public static String simpleFormPost(String uri, Map params) {
HttpPost httpPost = buildSimpleFormPost(uri, params, DEFAULT_REQUEST_CONFIG);
String responseString = simpleExecuteRequest(httpPost);
return responseString;
}
/**
* json payload提交请求,等价于:
* HttpPost httpPost = buildSimpleJsonPost(uri, jsonStr, DEFAULT_REQUEST_CONFIG);
*
return simpleExecuteRequest(httpPost);
*
* @param uri 指定的Uri
* @param jsonStr 不能为null
* @return
*/
public static String simpleJsonPost(String uri, String jsonStr) {
HttpPost httpPost = buildSimpleJsonPost(uri, jsonStr, DEFAULT_REQUEST_CONFIG);
String responseString = simpleExecuteRequest(httpPost);
return responseString;
}
public static HttpGet buildSimpleGet(String uri, Map params, RequestConfig reqConfig) throws URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(URI.create(uri));
if (params != null) {
// uriBuilder.setParameters(basicNameValuePairs);
Iterator> entryIterator = params.entrySet().iterator();
while (entryIterator.hasNext()) {
Entry entry = entryIterator.next();
if (entry.getValue() == null) {
uriBuilder.addParameter(entry.getKey(), "");
} else {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
}
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setConfig(reqConfig);
return httpGet;
}
public static HttpPost buildSimpleFormPost(String uri, Map params, RequestConfig reqConfig) {
ArrayList basicNameValuePairs = new ArrayList();
if (params != null) {
Iterator> entryIterator = params.entrySet().iterator();
while (entryIterator.hasNext()) {
Entry entry = entryIterator.next();
BasicNameValuePair pair = null;
if (entry.getValue() == null) {
pair = new BasicNameValuePair(entry.getKey(), "");
} else {
pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
}
basicNameValuePairs.add(pair);
}
}
HttpPost httpPost = new HttpPost(uri);
UrlEncodedFormEntity encodedParamsEntity = new UrlEncodedFormEntity(basicNameValuePairs, Consts.UTF_8);
httpPost.setEntity(encodedParamsEntity);
httpPost.setConfig(reqConfig);
return httpPost;
}
public static HttpPost buildSimpleJsonPost(String uri, String jsonStr, RequestConfig reqConfig) {
HttpPost httpPost = new HttpPost(uri);
StringEntity jsonStringEntity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
httpPost.setEntity(jsonStringEntity);
httpPost.setConfig(reqConfig);
return httpPost;
}
public static String simpleExecuteRequest(HttpUriRequest request) {
CopiedTextHttpResponse copiedHttpResponse = expectedTextExecuteRequest(request);
if (copiedHttpResponse == null) {
return null;
} else {
return copiedHttpResponse.getBody();
}
}
public static CopiedTextHttpResponse expectedTextExecuteRequest(HttpUriRequest request) {
CopiedTextHttpResponse copiedHttpResponse = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(request);
StatusLine statusLine = httpResponse.getStatusLine();
HttpEntity entity = httpResponse.getEntity();
String responseString = EntityUtils.toString(entity, Consts.UTF_8);
copiedHttpResponse = new CopiedTextHttpResponse(statusLine, httpResponse.getAllHeaders(), responseString);
} catch (IOException e) {
log.error("HttpHelper.expectedTextExecuteRequest() io error", e);
} finally {
HttpClientUtils.closeQuietly(httpResponse);
HttpClientUtils.closeQuietly(httpclient);
}
return copiedHttpResponse;
}
public static CopiedByteHttpResponse expectedBytesExecuteRequest(HttpUriRequest request) {
CopiedByteHttpResponse copiedHttpResponse = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(request);
StatusLine statusLine = httpResponse.getStatusLine();
HttpEntity entity = httpResponse.getEntity();
byte[] responseBytes = EntityUtils.toByteArray(entity);
copiedHttpResponse = new CopiedByteHttpResponse(statusLine, httpResponse.getAllHeaders(), responseBytes);
} catch (IOException e) {
log.error("HttpHelper.expectedBytesExecuteRequest() io error", e);
} finally {
HttpClientUtils.closeQuietly(httpResponse);
HttpClientUtils.closeQuietly(httpclient);
}
return copiedHttpResponse;
}
public static org.apache.http.client.config.RequestConfig.Builder defaultRequestConfigBuilder() {
return RequestConfig.custom().setConnectTimeout(DEFAULT_TIMEOUT).setSocketTimeout(DEFAULT_TIMEOUT);
}
}