| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714 |
- /*
- * FileName:HttpClientUtils.java
- * <p>
- * Copyright (c) 2017-2020, <a href="http://www.webcsn.com">hermit (794890569@qq.com)</a>.
- * <p>
- * Licensed under the GNU General Public License, Version 3 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.gnu.org/licenses/gpl-3.0.html
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
- package cn.com.lzt.common.util;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.google.common.collect.ImmutableMap;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- 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.utils.URLEncodedUtils;
- import org.apache.http.config.Registry;
- import org.apache.http.config.RegistryBuilder;
- import org.apache.http.conn.socket.ConnectionSocketFactory;
- import org.apache.http.conn.socket.PlainConnectionSocketFactory;
- import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.entity.mime.MultipartEntityBuilder;
- import org.apache.http.entity.mime.content.FileBody;
- import org.apache.http.entity.mime.content.StringBody;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClientBuilder;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.ssl.SSLContexts;
- import org.apache.http.util.EntityUtils;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import javax.net.ssl.SSLContext;
- import java.io.*;
- import java.net.URL;
- import java.net.URLConnection;
- import java.nio.charset.StandardCharsets;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- * HttpClient 搬砖工具类
- *
- *
- */
- public class HttpClientUtils {
- private static Logger logger = LogManager.getLogger(HttpClientUtils.class);
-
- private HttpClientUtils() {
- throw new IllegalAccessError("工具类不能实例化");
- }
- // private static BasicHttpClientConnectionManager connectionManager = null;
- private static PoolingHttpClientConnectionManager connectionManager = null;
- // private static HttpClientBuilder httpClientBuilder=null;
- private static RequestConfig requestConfig = RequestConfig.custom()
- .setSocketTimeout(30*1000)
- .setConnectTimeout(8000)
- .setConnectionRequestTimeout(6000)
- .build();
- static {
-
- SSLContext sslcontext = SSLContexts.createSystemDefault();
-
- // Create a registry of custom connection socket factories for supported //
- //protocol schemes.
-
-
- Registry<ConnectionSocketFactory> socketFactoryRegistry =
- RegistryBuilder.<ConnectionSocketFactory>create()
- .register("http", PlainConnectionSocketFactory.INSTANCE)
- .register("https", new SSLConnectionSocketFactory(sslcontext)) .build();
-
- // 使用基本的Httpclient链接器
- // connectionManager=new
- // BasicHttpClientConnectionManager(socketFactoryRegistry);
- connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
- // connectionManager = new PoolingHttpClientConnectionManager();
- connectionManager.setMaxTotal(1000);
- connectionManager.setDefaultMaxPerRoute(200);// 每个路由最大的请求数量
- // httpClientBuilder =
- // HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig);
- // HttpHost localhost = new HttpHost("http://www.baidu.com",80);
- // connectionManager.setMaxPerRoute(new HttpRoute(localhost), 200);
- }
- public static CloseableHttpClient getHttpClient() {
- return getHttpClientBuilder().build();
- }
- public static CloseableHttpClient getHttpClient(SSLContext sslContext) {
- return getHttpClientBuilder(sslContext).build();
- }
- public static HttpClientBuilder getHttpClientBuilder() {
- return HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig);
- // .setConnectionManagerShared(true);
- }
- public static HttpClientBuilder getHttpClientBuilder(SSLContext sslContext) {
- if (sslContext != null) {
- return getHttpClientBuilder().setSslcontext(sslContext);
- } else {
- return getHttpClientBuilder();
- }
- }
- /**
- * post 请求
- *
- * @param httpUrl
- * 请求地址
- * @param sslContext
- * ssl证书信息
- * @return
- */
- public static String sendHttpPost(String httpUrl, SSLContext sslContext) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- return sendHttpPost(httpPost, sslContext);
- }
- /**
- * 发送 post请求
- *
- * @param httpUrl
- * 地址
- */
- public static String sendHttpPost(String httpUrl) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- return sendHttpPost(httpPost, null);
- }
- /**
- * 发送 post请求
- *
- * @param httpUrl
- * 地址
- * @param params
- * 参数(格式:key1=value1&key2=value2)
- */
- public static String sendHttpPost(String httpUrl, String params) {
- return sendHttpPost(httpUrl, params, null);
- }
- /**
- * 发送 post请求
- *
- * @param httpUrl
- * 地址
- * @param params
- * 参数(格式:key1=value1&key2=value2)
- * @param sslContext
- * ssl证书信息
- */
- public static String sendHttpPost(String httpUrl, String params, SSLContext sslContext) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- try {
- // 设置参数
- StringEntity stringEntity = new StringEntity(params, "UTF-8");
- stringEntity.setContentType("application/x-www-form-urlencoded");
- httpPost.setEntity(stringEntity);
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- return sendHttpPost(httpPost, sslContext);
- }
- /**
- * 发送 post请求
- *
- * @param httpUrl
- * 地址
- * @param maps
- * 参数
- */
- public static String sendHttpPost(String httpUrl, Map<String, String> maps) {
- return sendHttpPost(httpUrl, maps, null);
- }
- public static String sendHttpPost(String httpUrl, List<String> maps) {
- return sendHttpPost(httpUrl, maps, null);
- }
- /**
- * 发送 post请求
- *
- * @param httpUrl
- * 地址
- * @param maps
- * 参数
- * @param sslContext
- * ssl证书信息
- */
- public static String sendHttpPost(String httpUrl, Map<String, String> maps, SSLContext sslContext) {
- HttpPost httpPost = wrapHttpPost(httpUrl, maps);
- return sendHttpPost(httpPost, null);
- }
- public static String sendHttpPost(String httpUrl, List<String> maps, SSLContext sslContext) {
- HttpPost httpPost = wrapHttpPost(httpUrl, maps);
- return sendHttpPost(httpPost, null);
- }
- public static String sendHttpPostWithHeader(
- String httpUrl, Map<String, String> maps, Map<String, String> headers) {
- HttpPost httpPost = wrapHttpPost(httpUrl, maps);
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- String key = entry.getKey();
- String value = entry.getValue();
- httpPost.setHeader(key, value);
- }
- return sendHttpPost(httpPost, null);
- }
- /**
- * 封装获取HttpPost方法
- *
- * @param httpUrl
- * @param maps
- * @return
- */
- public static HttpPost wrapHttpPost(String httpUrl, Map<String, String> maps) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- // 创建参数队列
- List<NameValuePair> nameValuePairs = new ArrayList<>();
- for (Map.Entry<String, String> m : maps.entrySet()) {
- nameValuePairs.add(new BasicNameValuePair(m.getKey(), m.getValue()));
- }
- try {
- httpPost.setHeader("Content-Type", "application/json");
- httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- return httpPost;
- }
- /**
- * 封装获取HttpPost方法
- *
- * @param httpUrl
- * @param entity
- * @return
- */
- public static HttpPost wrapHttpPost(String httpUrl, List<String> entity) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- try {
- httpPost.setHeader("Content-Type", "application/json");
- JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(entity));
- httpPost.setEntity(new StringEntity(jsonObject.toString(), StandardCharsets.UTF_8));
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- return httpPost;
- }
- /**
- * 发送 post请求(带文件)
- *
- * @param httpUrl
- * 地址
- * @param file
- * 附件,名称和File对应
- */
- public static String sendHttpPost(String httpUrl, File file) {
- return sendHttpPost(httpUrl, ImmutableMap.of( "media", file), null, null);
- }
- /**
- * 发送 post请求(带文件)
- *
- * @param httpUrl
- * 地址
- * @param file
- * 附件,名称和File对应
- * @param maps
- * 参数
- */
- public static String sendHttpPost(String httpUrl, File file, Map<String, String> maps) {
- return sendHttpPost(httpUrl, ImmutableMap.of( "media", file), maps, null);
- }
- /**
- * 发送 post请求(带文件),默认 files 名称数组.
- *
- * @param httpUrl
- * 地址
- * @param fileLists
- * 附件
- * @param maps
- * 参数
- */
- public static String sendHttpPost(String httpUrl, List<File> fileLists, Map<String, String> maps) {
- return sendHttpPost(httpUrl, fileLists, maps, null);
- }
- /**
- * 发送 post请求(带文件)
- *
- * @param httpUrl
- * 地址
- * @param fileMap
- * 附件,名称和File对应
- * @param maps
- * 参数
- */
- public static String sendHttpPost(String httpUrl, Map<String, File> fileMap, Map<String, String> maps) {
- return sendHttpPost(httpUrl, fileMap, maps, null);
- }
- /**
- * 发送 post请求(带文件),默认 files 名称数组.
- *
- * @param httpUrl
- * 地址
- * @param fileLists
- * 附件
- * @param maps
- * 参数
- * @param sslContext
- * ssl证书信息
- */
- public static String sendHttpPost(String httpUrl, List<File> fileLists, Map<String, String> maps,
- SSLContext sslContext) {
- Map<String, File> fileMap = new HashMap<>();
- if (fileLists==null||fileLists.isEmpty()) {
- for (File file : fileLists) {
- fileMap.put("media", file);
- }
- }
- return sendHttpPost(httpUrl, fileMap, maps, sslContext);
- }
- /**
- * 发送 post请求(带文件)
- *
- * @param httpUrl
- * 地址
- * @param fileMap
- * 附件,名称和File对应
- * @param maps
- * 参数
- * @param sslContext
- * ssl证书信息
- */
- public static String sendHttpPost(String httpUrl, Map<String, File> fileMap, Map<String, String> maps,
- SSLContext sslContext) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
- if (null != maps) {
- for (Map.Entry<String, String> m : maps.entrySet()) {
- meBuilder.addPart(m.getKey(), new StringBody(m.getValue(), ContentType.TEXT_PLAIN));
- }
- }
- if (null != fileMap) {
- for (Map.Entry<String, File> m : fileMap.entrySet()) {
- FileBody fileBody = new FileBody(m.getValue());
- meBuilder.addPart(m.getKey(), fileBody);
- }
- }
- HttpEntity reqEntity = meBuilder.build();
- httpPost.setEntity(reqEntity);
- return sendHttpPost(httpPost, sslContext);
- }
- /**
- * 发送Post请求
- *
- * @param httpPost
- * @return
- */
- public static String sendHttpPost(HttpPost httpPost) {
- return sendHttpPost(httpPost, null);
- }
- /**
- * 发送Post请求
- *
- * @param httpPost
- * @param sslConext
- * ssl证书信息
- * @return
- */
- public static String sendHttpPost(HttpPost httpPost, SSLContext sslConext) {
- httpPost.setConfig(requestConfig);
- httpPost.setHeader("Content-Type", "application/json");
- CloseableHttpClient httpClient = getHttpClient(sslConext);
- CloseableHttpResponse response = null;
- HttpEntity entity = null;
- String responseContent = null;
- try {
- // 执行请求
- response = httpClient.execute(httpPost);
- entity = response.getEntity();
- responseContent = EntityUtils.toString(entity, "UTF-8");
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- } finally {
- try {
- // 关闭连接,释放资源
- if (entity != null) {
- EntityUtils.consumeQuietly(entity); // 会自动释放连接
- }
- if (response != null) {
- response.close();
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- }
- return responseContent;
- }
- /**
- * 发送 get请求
- *
- * @param httpUrl
- */
- public static String sendHttpGet(String httpUrl, Map<String, String> params) {
- List<NameValuePair> nameValuePairs = new ArrayList<>();
- for (Map.Entry<String, String> m : params.entrySet()) {
- nameValuePairs.add(new BasicNameValuePair(m.getKey(), m.getValue()));
- }
- try {
- String paramsUri = URLEncodedUtils.format(nameValuePairs, "UTF-8");
- if(httpUrl.indexOf("?") > 0) {
- httpUrl = httpUrl + "&" + paramsUri;
- } else {
- httpUrl = httpUrl + "?" + paramsUri;
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- HttpGet httpGet = new HttpGet(httpUrl.replaceAll(" ", "%20"));// 创建get请求
- return sendHttpGet(httpGet, null);
- }
- // public static String sendHttpGet(String httpUrl) {
- //
- // }
- /**
- * 发送 get请求
- *
- * @param httpUrl
- * @param sslConext
- * ssl证书信息
- */
- public static String sendHttpGet(String httpUrl, SSLContext sslConext) {
- HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
- return sendHttpGet(httpGet, sslConext);
- }
- public static String sendHttpGet(String httpUrl) {
- return sendHttpGet(new HttpGet(httpUrl), null);
- }
- /**
- * 发送Get请求
- *
- * @param httpGet
- * @return
- */
- public static String sendHttpGet(HttpGet httpGet) {
- return sendHttpGet(httpGet, null);
- }
- /**
- * 发送Get请求
- *
- * @param httpGet
- * @param sslConext
- * ssl证书信息
- * @return
- */
- public static String sendHttpGet(HttpGet httpGet, SSLContext sslConext) {
- CloseableHttpClient httpClient = getHttpClient(sslConext);
- CloseableHttpResponse response = null;
- HttpEntity entity = null;
- String responseContent = null;
- try {
- // 执行请求
- response = httpClient.execute(httpGet);
- entity = response.getEntity();
- responseContent = EntityUtils.toString(entity, "UTF-8");
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- } finally {
- try {
- // 关闭连接,释放资源
- if (entity != null) {
- EntityUtils.consumeQuietly(entity); // 会自动释放连接
- }
- if (response != null) {
- response.close();
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- }
- return responseContent;
- }
- /**
- * 发送 get请求
- *
- * @param httpUrl
- * 请求路径
- * @param headers
- * 请求头参数
- * @return
- */
- public static String sendHttpHeaderGet(String httpUrl, Map<String, String> headers) {
- HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- String key = entry.getKey().toString();
- String value = entry.getValue().toString();
- httpGet.setHeader(key, value);
- }
- return sendHttpGet(httpGet, null);
- }
- /**
- * Get 下载文件
- *
- * @param httpUrl
- * @param file
- * @return
- */
- public static File sendHttpGetFile(String httpUrl, File file) {
- if (file == null) {
- return null;
- }
- HttpGet httpGet = new HttpGet(httpUrl);
- CloseableHttpClient httpClient = getHttpClient();
- CloseableHttpResponse response = null;
- HttpEntity entity = null;
- InputStream inputStream = null;
- FileOutputStream fileOutputStream = null;
- try {
- // 执行请求
- response = httpClient.execute(httpGet);
- entity = response.getEntity();
- inputStream = entity.getContent();
- fileOutputStream = new FileOutputStream(file);
- int len = 0;
- byte[] buf = new byte[1024];
- while ((len = inputStream.read(buf, 0, 1024)) != -1) {
- fileOutputStream.write(buf, 0, len);
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- } finally {
- try {
- if (fileOutputStream != null) {
- fileOutputStream.close();
- }
- if (inputStream != null) {
- inputStream.close();
- }
- // 关闭连接,释放资源
- if (entity != null) {
- EntityUtils.consumeQuietly(entity); // 会自动释放连接
- }
- if (response != null) {
- response.close();
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- }
- return file;
- }
-
-
- /**
- * Post 下载文件
- * @param httpUrl
- * @param maps
- * @param file
- * @return
- */
- public static File sendHttpPostFile(String httpUrl, Map<String, String> maps, File file) {
- if (file == null) {
- return null;
- }
- HttpPost httpPost=wrapHttpPost(httpUrl, maps);
- CloseableHttpClient httpClient = getHttpClient();
- CloseableHttpResponse response = null;
- HttpEntity entity = null;
- InputStream inputStream = null;
- FileOutputStream fileOutputStream = null;
- try {
- // 执行请求
- response = httpClient.execute(httpPost);
- entity = response.getEntity();
- inputStream = entity.getContent();
- fileOutputStream = new FileOutputStream(file);
- int len = 0;
- byte[] buf = new byte[1024];
- while ((len = inputStream.read(buf, 0, 1024)) != -1) {
- fileOutputStream.write(buf, 0, len);
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- } finally {
- try {
- if (fileOutputStream != null) {
- fileOutputStream.close();
- }
- if (inputStream != null) {
- inputStream.close();
- }
- // 关闭连接,释放资源
- if (entity != null) {
- EntityUtils.consumeQuietly(entity); // 会自动释放连接
- }
- if (response != null) {
- response.close();
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- }
- return file;
- }
- public static JSONObject sendHttpPostCarInfo(List<String> carIds){
- //定义接收数据
- JSONObject result = new JSONObject();
- String url = "http://47.101.51.219:10000/api/Carrier/RealtimePositon";
- HttpPost httpPost = new HttpPost(url);
- CloseableHttpClient client = HttpClients.createDefault();
- //请求参数转JOSN字符串
- String carIdsStr = carIds.toString();
- StringEntity entity = new StringEntity(carIdsStr, "UTF-8");
- entity.setContentEncoding("UTF-8");
- entity.setContentType("application/json");
- httpPost.setEntity(entity);
- try {
- HttpResponse response = client.execute(httpPost);
- if (response.getStatusLine().getStatusCode() == 200) {
- result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
- }
- } catch (IOException e) {
- e.printStackTrace();
- result.put("error", "连接错误!");
- }
- return result;
- }
- }
|