HttpUtil工具
import java.io.*;
import java.net.*;
import java.util.*;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
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.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class HttpUtil {
private static CloseableHttpClient httpClient = null;
private final static Object syncLock = new Object();
private static void config(HttpRequestBase httpRequestBase) {
// 配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(30000).setConnectTimeout(30000)
.setSocketTimeout(30000).build();
httpRequestBase.setConfig(requestConfig);
}
public static CloseableHttpClient getHttpClient(String url) {
String hostname = url.split("/")[2];
int port = 80;
if (hostname.contains(":")) {
String[] arr = hostname.split(":");
hostname = arr[0];
port = Integer.parseInt(arr[1]);
}
if (httpClient == null) {
synchronized (syncLock) {
if (httpClient == null) {
httpClient = createHttpClient(200, 40, 100, hostname, port);
}
}
}
return httpClient;
}
/**
* 创建HttpClient对象
*
* @create 2015年12月18日
*/
public static CloseableHttpClient createHttpClient(int maxTotal,
int maxPerRoute, int maxRoute, String hostname, int port) {
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory
.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory
.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder
.<ConnectionSocketFactory>create().register("http", plainsf)
.register("https", sslsf).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
registry);
cm.setMaxTotal(maxTotal);
cm.setDefaultMaxPerRoute(maxPerRoute);
HttpHost httpHost = new HttpHost(hostname, port);
cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
HttpRequestRetryHandler retry = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception,
int executionCount, HttpContext context) {
if (executionCount >= 5) {// 如果已经重试了5次,就放弃
return false;
}
if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
return false;
}
if (exception instanceof InterruptedIOException) {// 超时
return false;
}
if (exception instanceof UnknownHostException) {// 目标服务器不可达
return false;
}
if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
return false;
}
if (exception instanceof SSLException) {// SSL握手异常
return false;
}
HttpClientContext clientContext = HttpClientContext
.adapt(context);
HttpRequest request = clientContext.getRequest();
// 如果请求是幂等的,就再次尝试
if (!(request instanceof HttpEntityEnclosingRequest)) {
return true;
}
return false;
}
};
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm).setRetryHandler(retry).build();
return httpClient;
}
private static void setPostParams(HttpPost httpost,
Map<String, Object> params) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
}
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private static void setGetHeader(HttpGet httpget, Map<String, String> headers) {
Set<String> keySet = headers.keySet();
for (String key : keySet) {
httpget.addHeader(key, headers.get(key));
}
}
private static void setPostHeader(HttpPost httppost, Map<String, String> headers) {
Set<String> keySet = headers.keySet();
for (String key : keySet) {
httppost.addHeader(key, headers.get(key));
}
}
public static String httpPost(String url, Map<String, Object> params) {
return httpPost(url, params, null);
}
public static String httpPost(String url, String data) {
return httpPost(url, data, null);
}
public static String setUrl(String url, Map<String, Object> params) {
StringBuffer sb = new StringBuffer();// 存储参数
try {
if (params.size() == 1) {
for (String name : params.keySet()) {
sb.append(name).append("=").append(java.net.URLEncoder.encode(params.get(name).toString(), "UTF-8"));
}
} else {
for (String name : params.keySet()) {
sb.append(name).append("=").append(java.net.URLEncoder.encode(params.get(name).toString(), "UTF-8"))
.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url + "?" + sb.toString();
}
/**
* post请求
*
* @param url url地址
* @param params 参数
* @return
*/
public static String httpPost(String url, Map<String, Object> params,
Map<String, String> headers) {
HttpPost httppost = new HttpPost(url);
config(httppost);
setPostParams(httppost, params);
if (!StringUtils.isEmpty(headers)) {
setPostHeader(httppost, headers);
}
CloseableHttpResponse response = null;
try {
response = getHttpClient(url).execute(httppost,
HttpClientContext.create());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* post请求
*
* @param url url地址
* @param json 参数
* @return
*/
public static String httpPost(String url, String json,
Map<String, String> headers) {
HttpPost httppost = new HttpPost(url);
config(httppost);
if (!StringUtils.isEmpty(headers)) {
setPostHeader(httppost, headers);
}
CloseableHttpResponse response = null;
try {
StringEntity postingString = new StringEntity(json, "UTF-8");// json传递
httppost.setEntity(postingString);
response = getHttpClient(url).execute(httppost,
HttpClientContext.create());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发送get请求
*
* @param url 路径
* @return
*/
public static String httpGet(String url) {
return httpGet(url, null);
}
public static String httpGet(String url, Map<String, String> headers) {
HttpGet httpget = new HttpGet(url);
config(httpget);
if (!StringUtils.isEmpty(headers)) {
setGetHeader(httpget, headers);
}
CloseableHttpResponse response = null;
try {
response = getHttpClient(url).execute(httpget, HttpClientContext.create());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
System.out.println("error:" + url);
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static byte[] httpGetFile(String urlPath) {
InputStream is = null;
HttpURLConnection con = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
URL url = new URL(urlPath);
// 打开连接
con = (HttpURLConnection)url.openConnection();
// 输入流
is = con.getInputStream();
//byte [] bytes = new byte[is.available()]
byte [] bytes = new byte[102400];
int index = 0;
byteArrayOutputStream = new ByteArrayOutputStream();
while (-1 != (index = is.read(bytes,0,bytes.length))){
byteArrayOutputStream.write(bytes,0,index);
}
//is.read(bytes)
byte [] resultBytes = byteArrayOutputStream.toByteArray();
return resultBytes;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
}
}
请求图片
@SysLog(serviceId = FisherServiceNameConstants.FISHER_MAP_SERVICE, moduleName = MODULE_NAME, actionName = "海图瓦片接口")
@ApiOperation(value = "海图瓦片接口", notes = "海图瓦片接口", httpMethod = "GET")
@GetMapping("/{x}/{y}/{z}")
public ResponseEntity<byte[]> mapImg(@PathVariable String x, @PathVariable String y, @PathVariable String z) {
String url = "https://xxxx/map/" + x + "/" + y + "/" + z;
byte[] bytes= HttpUtil.httpGetFile(url);
HttpHeaders headers = new HttpHeaders();
headers.add("content-type", "image/png");
headers.add("Cache-Control", "max-age=300");
return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
}