com.loocme.sys.util.HttpUtil Maven / Gradle / Ivy
package com.loocme.sys.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;
import com.loocme.security.encrypt.Base64;
import com.loocme.sys.constance.DateFormatConst;
import com.loocme.sys.constance.RegConst;
import com.loocme.sys.exception.HttpConnectionException;
/**
*
* Class : FlightPaymentUtil
*
* @author liuchi
*/
@Slf4j
public class HttpUtil
{
private static final String HTTP_APPLICATION_TYPE_JSON = "json";
private static final String HTTP_APPLICATION_TYPE_OCTETSTREAM = "octet-stream";
private static final int DEFAULT_VALUE_READ_BUFFER_SIZE = 100;
private static String priEncoding;
private static int priTimeout = 0;
public static String post(String url, String encoding, String content)
throws HttpConnectionException
{
if (StringUtil.isNull(encoding))
{
encoding = priEncoding;
}
return post(url, encoding, priTimeout, null,
RequestUtil.getReqParams(content));
}
public static String post(String url, String content)
throws HttpConnectionException
{
return post(url, priEncoding, content);
}
public static String post(String url, Map headerMap,
String content) throws HttpConnectionException
{
return post(url, priEncoding, priTimeout, headerMap,
RequestUtil.getReqParams(content));
}
public static String post(String url, String encoding,
Map headerMap, String content)
throws HttpConnectionException
{
if (StringUtil.isNull(encoding))
{
encoding = priEncoding;
}
return post(url, encoding, priTimeout, headerMap,
RequestUtil.getReqParams(content));
}
public static String post(String url, Map requestParams)
throws HttpConnectionException
{
return post(url, priEncoding, priTimeout, null, requestParams);
}
public static String post(String url, Map headerMap,
Map requestParams) throws HttpConnectionException
{
return post(url, priEncoding, priTimeout, headerMap, requestParams);
}
public static String post(String url, String encoding,
Map headerMap, Map requestParams)
throws HttpConnectionException
{
if (StringUtil.isNull(encoding))
{
encoding = priEncoding;
}
return post(url, encoding, priTimeout, headerMap, requestParams);
}
public static String post(String url, String encoding, int timeout,
Map headerMap, Map requestParams)
throws HttpConnectionException
{
log.debug("开始http调用地址:" + url);
Request request = Request.Post(url);
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
if (0 != timeout)
{
request.socketTimeout(timeout);
}
if (MapUtil.isNotNull(requestParams))
{
NameValuePair[] params = new NameValuePair[requestParams.keySet().size()];
Iterator it = requestParams.keySet().iterator();
int count = 0;
while (it.hasNext())
{
String key = it.next();
params[count++] = new BasicNameValuePair(key, requestParams.get(key));
}
request.bodyForm(params);
}
if (MapUtil.isNotNull(headerMap))
{
Iterator it = headerMap.keySet().iterator();
while (it.hasNext())
{
String headerName = it.next();
request.addHeader(headerName, headerMap.get(headerName));
}
}
log.debug("请求header信息:" + headerMap);
log.debug("请求参数信息:" + requestParams);
try
{
log.debug("开始调用:");
HttpResponse response = request.execute().returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
log.debug("返回http响应码:" + statusCode);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [http status] %d [resp] ", url, headerMap, requestParams, statusCode));
throw new HttpConnectionException(statusCode);
}
String responseStr = FileUtil.read(response.getEntity().getContent());
log.debug("响应信息:" + responseStr);
return responseStr;
}
catch (SocketTimeoutException e)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [resp] ", url, headerMap, requestParams), e);
throw new HttpConnectionException(98, e.getMessage());
}
catch (IOException e)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [resp] ", url, headerMap, requestParams), e);
throw new HttpConnectionException(e);
}
}
public static String postBytes(String url, byte[] body)
throws HttpConnectionException
{
return postBytes(url, priEncoding, priTimeout, null, null, null, body);
}
public static String postBytes(String url, String contentType, byte[] body)
throws HttpConnectionException
{
return postBytes(url, priEncoding, priTimeout, null, null, contentType, body);
}
public static String postBytes(String url, Map requestParams, byte[] body)
throws HttpConnectionException
{
return postBytes(url, priEncoding, priTimeout, null, requestParams, null, body);
}
public static String postBytes(String url, Map headerMap, Map requestParams, byte[] body)
throws HttpConnectionException
{
return postBytes(url, priEncoding, priTimeout, headerMap, requestParams, null, body);
}
public static String postBytes(String url, Map headerMap, Map requestParams, String contentType, byte[] body)
throws HttpConnectionException
{
return postBytes(url, priEncoding, priTimeout, headerMap, requestParams, contentType, body);
}
public static String postBytes(String url, String encoding, int timeout,
Map headerMap, Map requestParams, String contentType, byte[] body)
throws HttpConnectionException
{
log.debug("开始http调用地址:" + url);
Request request = Request.Post(url);
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Content-Type", StringUtil.isNull(contentType)?"binary/octet-stream":contentType);
if (0 != timeout)
{
request.socketTimeout(timeout);
}
if (MapUtil.isNotNull(requestParams))
{
NameValuePair[] params = new NameValuePair[requestParams.keySet().size()];
Iterator it = requestParams.keySet().iterator();
int count = 0;
while (it.hasNext())
{
String key = it.next();
params[count++] = new BasicNameValuePair(key, requestParams.get(key));
}
request.bodyForm(params);
}
if (MapUtil.isNotNull(headerMap))
{
Iterator it = headerMap.keySet().iterator();
while (it.hasNext())
{
String headerName = it.next();
request.addHeader(headerName, headerMap.get(headerName));
}
}
if (null != body)
{
request.bodyByteArray(body);
}
log.debug("请求header信息:" + headerMap);
log.debug("请求参数信息:" + requestParams);
String errLogStr = String.format("[http error post] [url] %s [header] %s [param] %s [bytelength] %d [resp] ", url, headerMap, requestParams, null == body ? 0 : body.length);
try
{
log.debug("开始调用:");
HttpResponse response = request.execute().returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
log.debug("返回http响应码:" + statusCode);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [http status] %d [resp] ", url, headerMap, requestParams, statusCode));
throw new HttpConnectionException(statusCode);
}
String responseStr = FileUtil.read(response.getEntity().getContent());
log.debug("响应信息:" + responseStr);
return responseStr;
}
catch (SocketTimeoutException e)
{
log.error(errLogStr, e);
throw new HttpConnectionException(98, e.getMessage());
}
catch (IOException e)
{
log.error(errLogStr, e);
throw new HttpConnectionException(e);
}
}
public static byte[] postProtobuf(String url, int timeout, Map headerMap, Map requestParams, String contentType, byte[] body) throws HttpConnectionException
{
log.debug("开始http调用地址:" + url);
Request request = Request.Post(url);
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Content-Type", StringUtil.isNull(contentType)?"binary/octet-stream":contentType);
if (0 != timeout)
{
request.socketTimeout(timeout);
}
if (MapUtil.isNotNull(requestParams))
{
NameValuePair[] params = new NameValuePair[requestParams.keySet().size()];
Iterator it = requestParams.keySet().iterator();
int count = 0;
while (it.hasNext())
{
String key = it.next();
params[count++] = new BasicNameValuePair(key, requestParams.get(key));
}
request.bodyForm(params);
}
if (MapUtil.isNotNull(headerMap))
{
Iterator it = headerMap.keySet().iterator();
while (it.hasNext())
{
String headerName = it.next();
request.addHeader(headerName, headerMap.get(headerName));
}
}
if (null != body)
{
request.bodyByteArray(body);
}
log.debug("请求header信息:" + headerMap);
log.debug("请求参数信息:" + requestParams);
String errLogStr = String.format("[http error post] [url] %s [header] %s [param] %s [bytelength] %d [resp] ", url, headerMap, requestParams, null == body ? 0 : body.length);
try
{
log.debug("开始调用:");
HttpResponse response = request.execute().returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
log.debug("返回http响应码:" + statusCode);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [http status] %d [resp] ", url, headerMap, requestParams, statusCode));
throw new HttpConnectionException(statusCode);
}
return input2byte(response.getEntity().getContent());
}
catch (SocketTimeoutException e)
{
log.error(errLogStr, e);
throw new HttpConnectionException(98, e.getMessage());
}
catch (IOException e)
{
log.error(errLogStr, e);
throw new HttpConnectionException(e);
}
}
public static String delete(String url)
throws HttpConnectionException
{
return delete(url, 0, null);
}
public static String delete(String url, int timeout,
Map headerMap)
throws HttpConnectionException
{
log.debug("开始http调用地址:" + url);
Request request = Request.Delete(url);
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
if (0 != timeout)
{
request.socketTimeout(timeout);
}
if (MapUtil.isNotNull(headerMap))
{
Iterator it = headerMap.keySet().iterator();
while (it.hasNext())
{
String headerName = it.next();
request.addHeader(headerName, headerMap.get(headerName));
}
}
log.debug("请求header信息:" + headerMap);
try
{
log.debug("开始调用:");
HttpResponse response = request.execute().returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
log.debug("返回http响应码:" + statusCode);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
{
log.error(String.format("[http error post] [url] %s [header] %s [http status] %d [resp] ", url, headerMap, statusCode));
throw new HttpConnectionException(statusCode);
}
String responseStr = FileUtil.read(response.getEntity().getContent());
log.debug("响应信息:" + responseStr);
return responseStr;
}
catch (SocketTimeoutException e)
{
log.error(String.format("[http error delete] [url] %s [header] %s [resp] ", url, headerMap), e);
throw new HttpConnectionException(98, e.getMessage());
}
catch (IOException e)
{
log.error(String.format("[http error delete] [url] %s [header] %s [resp] ", url, headerMap), e);
throw new HttpConnectionException(e);
}
}
public static String putContent(String url, String contentType, String content)
throws HttpConnectionException
{
return putContent(url, null, 0, null, contentType, content);
}
public static String putContent(String url, String encoding, int timeout,
Map headerMap, String contentType, String content)
throws HttpConnectionException
{
log.debug("开始http调用地址:" + url);
Request request = Request.Put(url);
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Content-Type", contentType);
if (0 != timeout)
{
request.socketTimeout(timeout);
}
if (MapUtil.isNotNull(headerMap))
{
Iterator it = headerMap.keySet().iterator();
while (it.hasNext())
{
String headerName = it.next();
request.addHeader(headerName, headerMap.get(headerName));
}
}
request.bodyString(content, ContentType.parse(contentType));
log.debug("请求header信息:" + headerMap);
log.debug("请求参数类型:" + contentType);
log.debug("请求参数信息:" + content);
log.debug("请求开始时间:" + DateUtil.getFormat(new Date(), DateFormatConst.YMDHMSMS_));
try
{
log.debug("开始调用:");
HttpResponse response = request.execute().returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
log.debug("返回http响应码:" + statusCode);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [http status] %d [resp] ", url, headerMap, content, statusCode));
throw new HttpConnectionException(statusCode);
}
log.debug("请求结束时间:" + DateUtil.getFormat(new Date(), DateFormatConst.YMDHMSMS_));
String responseStr = FileUtil.read(response.getEntity().getContent());
log.debug("响应信息:" + responseStr);
return responseStr;
}
catch (SocketTimeoutException e)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [resp] ", url, headerMap, content), e);
throw new HttpConnectionException(98, e.getMessage());
}
catch (IOException e)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [resp] ", url, headerMap, content), e);
throw new HttpConnectionException(e);
}
}
public static String get(String url, String encoding, String content)
throws HttpConnectionException
{
if (StringUtil.isNull(encoding))
{
encoding = priEncoding;
}
return get(url, encoding, priTimeout, null, content);
}
public static String get(String url, String content)
throws HttpConnectionException
{
return get(url, priEncoding, content);
}
public static String get(String url, Map headerMap,
String content) throws HttpConnectionException
{
return get(url, priEncoding, priTimeout, headerMap, content);
}
public static String get(String url, String encoding,
Map headerMap, String content)
throws HttpConnectionException
{
if (StringUtil.isNull(encoding))
{
encoding = priEncoding;
}
return get(url, encoding, priTimeout, headerMap, content);
}
public static String get(String url, Map requestParams)
throws HttpConnectionException
{
return get(url, priEncoding, priTimeout, null,
RequestUtil.getReqContent(requestParams));
}
public static String get(String url, Map headerMap,
Map requestParams) throws HttpConnectionException
{
return get(url, priEncoding, priTimeout, headerMap,
RequestUtil.getReqContent(requestParams));
}
public static String get(String url, String encoding,
Map headerMap, Map requestParams)
throws HttpConnectionException
{
if (StringUtil.isNull(encoding))
{
encoding = priEncoding;
}
return get(url, encoding, priTimeout, headerMap,
RequestUtil.getReqContent(requestParams));
}
public static String get(String url, String encoding, int timeout,
Map headerMap, String content)
throws HttpConnectionException
{
if (null != url && StringUtil.isNotNull(content))
{
url = url + (url.indexOf("?") != -1 ? "&" : "?") + content;
}
log.debug("开始http调用地址:" + url);
Request request = Request.Get(url);
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
if (0 != timeout)
{
request.socketTimeout(timeout);
}
if (MapUtil.isNotNull(headerMap))
{
Iterator it = headerMap.keySet().iterator();
while (it.hasNext())
{
String headerName = it.next();
request.addHeader(headerName, headerMap.get(headerName));
}
}
log.debug("请求header信息:" + headerMap);
log.debug("请求参数信息:" + content);
try
{
log.debug("开始调用:");
HttpResponse response = request.execute().returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
log.debug("返回http响应码:" + statusCode);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [http status] %d [resp] ", url, headerMap, content, statusCode));
throw new HttpConnectionException(statusCode);
}
String responseStr = FileUtil.read(response.getEntity().getContent());
log.debug("响应信息:" + responseStr);
return responseStr;
}
catch (SocketTimeoutException e)
{
log.error(String.format("[http error get] [url] %s [header] %s [param] %s [resp] ", url, headerMap, content), e);
throw new HttpConnectionException(98, e.getMessage());
}
catch (IOException e)
{
log.error(String.format("[http error get] [url] %s [header] %s [param] %s [resp] ", url, headerMap, content), e);
throw new HttpConnectionException(e);
}
}
public static String postContent(String url, String encoding,
String contentType, String content) throws HttpConnectionException
{
if (StringUtil.isNull(encoding))
{
encoding = priEncoding;
}
return postContent(url, encoding, priTimeout, null, contentType, content);
}
public static String postContent(String url, String content)
throws HttpConnectionException
{
return postContent(url, priEncoding, content);
}
public static String postContent(String url, String contentType,
String content) throws HttpConnectionException
{
return postContent(url, priEncoding, priTimeout, null, contentType, content);
}
public static String postContent(String url, Map headerMap,
String contentType, String content) throws HttpConnectionException
{
return postContent(url, priEncoding, priTimeout, headerMap, contentType,
content);
}
public static String postContent(String url, String encoding,
Map headerMap, String contentType, String content)
throws HttpConnectionException
{
if (StringUtil.isNull(encoding))
{
encoding = priEncoding;
}
return postContent(url, encoding, priTimeout, headerMap, contentType,
content);
}
public static String postContent(String url, String encoding, int timeout,
Map headerMap, String contentType, String content)
throws HttpConnectionException
{
log.debug("开始http调用地址:" + url);
Request request = Request.Post(url);
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Content-Type", contentType);
if (0 != timeout)
{
request.socketTimeout(timeout);
}
if (MapUtil.isNotNull(headerMap))
{
Iterator it = headerMap.keySet().iterator();
while (it.hasNext())
{
String headerName = it.next();
request.addHeader(headerName, headerMap.get(headerName));
}
}
if (StringUtil.isNotNull(content))
{
request.bodyString(content, ContentType.parse(contentType));
}
log.debug("请求header信息:" + headerMap);
log.debug("请求参数类型:" + contentType);
log.debug("请求参数信息:" + content);
log.debug("请求开始时间:" + DateUtil.getFormat(new Date(), DateFormatConst.YMDHMSMS_));
try
{
log.debug("开始调用:");
HttpResponse response = request.execute().returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
log.debug("返回http响应码:" + statusCode);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [http status] %d [resp] ", url, headerMap, content, statusCode));
throw new HttpConnectionException(statusCode);
}
log.debug("请求结束时间:" + DateUtil.getFormat(new Date(), DateFormatConst.YMDHMSMS_));
String responseStr = FileUtil.read(response.getEntity().getContent());
log.debug("响应信息:" + responseStr);
return responseStr;
}
catch (SocketTimeoutException e)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [resp] ", url, headerMap, content), e);
throw new HttpConnectionException(98, e.getMessage());
}
catch (IOException e)
{
log.error(String.format("[http error post] [url] %s [header] %s [param] %s [resp] ", url, headerMap, content), e);
throw new HttpConnectionException(e);
}
}
public static void download(String url, File file)
throws HttpConnectionException
{
download(url, priEncoding, null, file);
}
public static void download(String url, String content, File file)
throws HttpConnectionException
{
download(url, priEncoding, content, file);
}
public static void download(String url, String encoding, String content,
File file) throws HttpConnectionException
{
if (StringUtil.isNotNull(content))
{
url += (url.indexOf("?") != -1 ? "&" : "?") + content;
}
if (StringUtil.isNull(encoding))
{
encoding = priEncoding;
}
// 请求路径中包含中文
String[] matches = PatternUtil.getMatch(url,
RegConst.CHINESECODE, Pattern.CASE_INSENSITIVE);
try
{
while (null != matches)
{
url = url.replaceFirst(matches[0], URLEncoder.encode(matches[0], "UTF-8"));
matches = PatternUtil.getMatch(url,
RegConst.CHINESECODE, Pattern.CASE_INSENSITIVE);
}
}
catch (UnsupportedEncodingException e1)
{
log.error(" ", e1);
}
Request request = Request.Get(url);
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.addHeader("Referer", "https://www.baidu.com");
try
{
HttpResponse response = request.execute().returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
{
log.error(String.format("[http error post] [url] %s [param] %s [http status] %d [resp] ", url, content, statusCode));
throw new HttpConnectionException(statusCode);
}
Header contentTypeHeader = response.getLastHeader("Content-Type");
String type = PatternUtil.getMatch(contentTypeHeader.getValue(),
"application/(json|octet-stream)",
Pattern.CASE_INSENSITIVE, 1);
if (HTTP_APPLICATION_TYPE_JSON.equalsIgnoreCase(type))
{
String responseStr = FileUtil.read(response.getEntity().getContent());
throw new HttpConnectionException(99, responseStr);
}
else if (HTTP_APPLICATION_TYPE_OCTETSTREAM.equalsIgnoreCase(type))
{
FileUtil.write(file, response.getEntity().getContent());
}
}
catch (SocketTimeoutException e)
{
log.error(String.format("[http error download] [url] %s [param] %s [resp] ", url, content), e);
throw new HttpConnectionException(98, e.getMessage());
}
catch (IOException e)
{
log.error(String.format("[http error download] [url] %s [param] %s [resp] ", url, content), e);
throw new HttpConnectionException(e);
}
}
public static String downloadImgBase64(String url)
throws HttpConnectionException
{
byte[] by = downloadImage(url);
return null == by?null:new String(Base64.encode(by));
}
public static byte[] downloadImage(String url)
throws HttpConnectionException
{
// 请求路径中包含中文
String[] matches = PatternUtil.getMatch(url, RegConst.CHINESECODE,
Pattern.CASE_INSENSITIVE);
try
{
while (null != matches)
{
url = url.replaceFirst(matches[0],
URLEncoder.encode(matches[0], "UTF-8"));
matches = PatternUtil.getMatch(url, RegConst.CHINESECODE,
Pattern.CASE_INSENSITIVE);
}
}
catch (UnsupportedEncodingException e1)
{
log.error("", e1);
}
Request request = Request.Get(url);
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.addHeader("Referer", "https://www.baidu.com");
try
{
HttpResponse response = request.execute().returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
{
log.error(String.format("[http error post] [url] %s [http status] %d [resp] ", url, statusCode));
throw new HttpConnectionException(statusCode);
}
byte[] by = input2byte(response.getEntity().getContent());
return by;
}
catch (SocketTimeoutException e)
{
log.error(String.format("[http error download] [url] %s [resp] ", url), e);
throw new HttpConnectionException(98, e.getMessage());
}
catch (IOException e)
{
log.error(String.format("[http error download] [url] %s [resp] ", url), e);
throw new HttpConnectionException(e);
}
}
public static final byte[] input2byte(InputStream inStream)
throws IOException
{
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[DEFAULT_VALUE_READ_BUFFER_SIZE];
int rc = 0;
while ((rc = inStream.read(buff, 0, DEFAULT_VALUE_READ_BUFFER_SIZE)) > 0)
{
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy