123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516 |
- package com.huimv.business.utils;
- import com.alibaba.fastjson.JSONObject;
- import org.apache.http.HttpEntity;
- 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.*;
- 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.springframework.stereotype.Component;
- import java.io.IOException;
- import java.util.*;
- /**
- * @Project : huimv.shiwan
- * @Package : com.huimv.biosafety.uface.controller
- * @Description : TODO
- * @Version : 1.0
- * @Author : ZhuoNing
- * @Create : 2020-12-25
- **/
- @Component
- public class HttpTemplete {
- private String testHttpIp = "http://localhost:9105";
- // public static void main(String[] args) throws Exception {
- // //
- // HttpTemplete client = new HttpTemplete();
- //// client.testGetRequest1();
- // client.testGetRequest2();
- // }
- private Integer connectTimeout = null;
- private Integer requestTimeout = null;
- private Integer socketTimeout = null;
- static {
- }
- //发送简单数据
- public void doPostSimple(String serviceUrl,String data){
- System.out.println("推送数据地址:"+serviceUrl);
- //
- Map<String,String> paramsMap = new HashMap<String,String>();
- paramsMap.put("data", data);
- //
- Map<String,Integer> timeoutMap = new HashMap<String,Integer>();
- timeoutMap.put("connectTimeout", 5000);
- timeoutMap.put("requestTimeout", 5000);
- timeoutMap.put("socketTimeout", 5000);
- try{
- // 用Post方法推送接口数据
- doPost(serviceUrl,paramsMap,timeoutMap);
- } catch (IOException e) {
- System.out.println("###错误信息:"+e.getMessage());
- }
- }
- /**
- * @Method : doPost
- * @Description : post方式推送接口
- * @Params : [url, paramsMap, timeoutMap]
- * @Return : com.alibaba.fastjson.JSONObject
- *
- * @Author : ZhuoNing
- * @Date : 2021/11/19
- * @Time : 14:55
- */
- public JSONObject doPost(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
- // 创建默认的httpClient实例.
- CloseableHttpClient httpClient = getHttpClientConnection();
- //
- int connectTimeout = timeoutMap.get("connectTimeout");
- int requestTimeout = timeoutMap.get("requestTimeout");
- int socketTimeout = timeoutMap.get("socketTimeout");
- // 创建httpPost
- HttpPost httpPost = new HttpPost(url);
- RequestConfig requestConfig = RequestConfig.custom()
- .setSocketTimeout(socketTimeout) //服务器响应超时时间
- .setConnectTimeout(connectTimeout) //连接服务器超时时间
- .setConnectionRequestTimeout(requestTimeout)
- .build();
- httpPost.setConfig(requestConfig);
- // 创建参数队列
- List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
- Set<Map.Entry<String, String>> entrySet = paramsMap.entrySet();
- for (Map.Entry<String, String> e : entrySet) {
- String name = e.getKey();
- String value = e.getValue();
- NameValuePair pair = new BasicNameValuePair(name, value);
- paramsList.add(pair);
- }
- UrlEncodedFormEntity content = new UrlEncodedFormEntity(paramsList, "UTF-8");
- //处理乱码
- // StringEntity content = new StringEntity(paramsList.toString(), Charset.forName("UTF-8"));// 第二个参数,设置后才会对,内容进行编码
- // content.setContentType("application/soap+xml; charset=UTF-8");
- // content.setContentEncoding("UTF-8");
- httpPost.setEntity(content);
- // HttpUriRequest httpPost = RequestBuilder.post().setUri(url).setEntity(content).setConfig(requestConfig);
- CloseableHttpResponse response = httpClient.execute(httpPost);
- // 获取响应实体
- HttpEntity entity = response.getEntity();
- try {
- if (response.getStatusLine().getStatusCode() == 200) {
- // 打印响应内容
- String text = EntityUtils.toString(entity, "utf-8");
- JSONObject resultJo = new JSONObject();
- resultJo.put("status", true);
- resultJo.put("content", text);
- return resultJo;
- }else{
- String text = EntityUtils.toString(entity, "utf-8");
- JSONObject resultJo = new JSONObject();
- resultJo.put("status", false);
- resultJo.put("content", text);
- return resultJo;
- }
- } finally {
- //释放资源
- if (response != null) {
- response.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- }
- }
- /**
- * @Method : setTimeout
- * @Description :
- * @Params : [connectTimeout, requestTimeout, socketTimeout]
- * @Return : void
- *
- * @Author : ZhuoNing
- * @Date : 2021/11/23
- * @Time : 9:36
- */
- public Map<String, Integer> setTimeout(Integer connectTimeout, Integer requestTimeout, Integer socketTimeout){
- //
- if(connectTimeout == null){
- this.connectTimeout = 3000;
- }else{
- this.connectTimeout = connectTimeout;
- }
- //
- if(requestTimeout == null){
- this.requestTimeout = 3000;
- }else{
- this.requestTimeout = requestTimeout;
- }
- //
- if(socketTimeout == null){
- this.socketTimeout = 3000;
- }else{
- this.socketTimeout = socketTimeout;
- }
- Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
- timeoutMap.put("connectTimeout", this.connectTimeout);
- timeoutMap.put("requestTimeout", this.requestTimeout);
- timeoutMap.put("socketTimeout", this.socketTimeout);
- return timeoutMap;
- }
- /**
- * @Method : setTimeout
- * @Description :
- * @Params : [connectTimeout, requestTimeout, socketTimeout]
- * @Return : java.util.Map<java.lang.String,java.lang.Integer>
- *
- * @Author : ZhuoNing
- * @Date : 2021/11/23
- * @Time : 9:41
- */
- public Map<String, Integer> setTimeout(String connectTimeout, String requestTimeout, String socketTimeout){
- //
- if(connectTimeout == null){
- this.connectTimeout = 3000;
- }else{
- this.connectTimeout = Integer.parseInt(connectTimeout);
- }
- //
- if(requestTimeout == null){
- this.requestTimeout = 3000;
- }else{
- this.requestTimeout = Integer.parseInt(requestTimeout);
- }
- //
- if(socketTimeout == null){
- this.socketTimeout = 3000;
- }else{
- this.socketTimeout = Integer.parseInt(socketTimeout);
- }
- Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
- timeoutMap.put("connectTimeout", this.connectTimeout);
- timeoutMap.put("requestTimeout", this.requestTimeout);
- timeoutMap.put("socketTimeout", this.socketTimeout);
- return timeoutMap;
- }
- /**
- * @Method : doGet
- * @Description :
- * @Params : [url, paramsMap]
- * @Return : com.alibaba.fastjson.JSONObject
- *
- * @Author : ZhuoNing
- * @Date : 2021/11/23
- * @Time : 9:34
- */
- public JSONObject doGet(String url, Map<String, String> paramsMap) throws IOException {
- //
- if(this.connectTimeout == null){
- this.connectTimeout = 3000;
- }
- //
- if(this.requestTimeout == null)
- {
- this.requestTimeout = 3000;
- }
- //
- if(this.socketTimeout == null){
- this.socketTimeout = 3000;
- }
- Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
- timeoutMap.put("connectTimeout", this.connectTimeout);
- timeoutMap.put("requestTimeout", this.requestTimeout);
- timeoutMap.put("socketTimeout", this.socketTimeout);
- //
- CloseableHttpClient httpClient = getHttpClientConnection();
- //执行//获取请求内容
- CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
- try {
- // 获取响应实体
- HttpEntity entity = response.getEntity();
- // 打印响应状态
- if (response.getStatusLine().getStatusCode() == 200) {
- // 打印响应内容
- String text = EntityUtils.toString(entity, "utf-8");
- JSONObject resultJo = new JSONObject();
- resultJo.put("status", true);
- resultJo.put("content", text);
- return resultJo;
- } else {
- String text = EntityUtils.toString(entity, "utf-8");
- JSONObject resultJo = new JSONObject();
- resultJo.put("status", false);
- resultJo.put("content", text);
- return resultJo;
- }
- } finally {
- //释放资源
- if (response != null) {
- response.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- }
- }
- private CloseableHttpClient httpClient = null;
- private CloseableHttpResponse response = null;
- public JSONObject doGetBatch(String url, Map<String, String> paramsMap) throws IOException {
- //
- if(this.connectTimeout == null){
- this.connectTimeout = 3000;
- }
- //
- if(this.requestTimeout == null)
- {
- this.requestTimeout = 3000;
- }
- //
- if(this.socketTimeout == null){
- this.socketTimeout = 3000;
- }
- Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
- timeoutMap.put("connectTimeout", this.connectTimeout);
- timeoutMap.put("requestTimeout", this.requestTimeout);
- timeoutMap.put("socketTimeout", this.socketTimeout);
- //
- httpClient = getHttpClientConnection();
- //执行//获取请求内容
- response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
- // 获取响应实体
- HttpEntity entity = response.getEntity();
- // 打印响应状态
- if (response.getStatusLine().getStatusCode() == 200) {
- // 打印响应内容
- String text = EntityUtils.toString(entity, "utf-8");
- JSONObject resultJo = new JSONObject();
- resultJo.put("status", true);
- resultJo.put("content", text);
- return resultJo;
- } else {
- String text = EntityUtils.toString(entity, "utf-8");
- JSONObject resultJo = new JSONObject();
- resultJo.put("status", false);
- resultJo.put("content", text);
- return resultJo;
- }
- }
- //关闭http连接
- public void closeHttpConn() throws IOException {
- System.out.println("开始释放http连接资源");
- //释放资源
- if (response != null) {
- response.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- }
- /**
- * @Method : doGet
- * @Description :get方式推送接口
- * @Params : [url, paramsMap, timeoutMap]
- * @Return : com.alibaba.fastjson.JSONObject
- * @Author : ZhuoNing
- * @Date : 2021/11/18
- * @Time : 17:39
- */
- public JSONObject doGet(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
- if (timeoutMap == null) {
- timeoutMap.put("connectTimeout", 5000);
- timeoutMap.put("requestTimeout", 5000);
- timeoutMap.put("socketTimeout", 5000);
- }
- //
- CloseableHttpClient httpClient = getHttpClientConnection();
- //执行//获取请求内容
- CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
- try {
- // 获取响应实体
- HttpEntity entity = response.getEntity();
- // 打印响应状态
- if (response.getStatusLine().getStatusCode() == 200) {
- // 打印响应内容
- String text = EntityUtils.toString(entity, "utf-8");
- JSONObject resultJo = new JSONObject();
- resultJo.put("status", true);
- resultJo.put("content", text);
- return resultJo;
- } else {
- String text = EntityUtils.toString(entity, "utf-8");
- JSONObject resultJo = new JSONObject();
- resultJo.put("status", false);
- resultJo.put("content", text);
- return resultJo;
- }
- } finally {
- //释放资源
- if (response != null) {
- response.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- }
- }
- private void testGetRequest1() throws IOException {
- Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
- timeoutMap.put("connectTimeout", 5000);
- timeoutMap.put("requestTimeout", 5000);
- timeoutMap.put("socketTimeout", 5000);
- String url = testHttpIp + "/token/getToken?userId=20210501×tamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
- // test error
- url = testHttpIp + "/token/getToken?userId=20210501×tamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c&userId=20210501×tamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
- CloseableHttpClient httpClient = getHttpClientConnection();
- CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, timeoutMap));
- // 打印响应状态
- System.out.println("响应状态1 =" + response.getStatusLine());
- try {
- if (response.getStatusLine().getStatusCode() == 200) {
- // 获取响应实体
- HttpEntity entity = response.getEntity();
- // 打印响应内容
- String text = EntityUtils.toString(entity, "utf-8");
- System.out.println("响应内容=" + text);
- JSONObject resultJo = JSONObject.parseObject(text);
- System.out.println("accessToken=" + resultJo.getString("accessToken"));
- } else {
- System.out.println("请求失败");
- }
- } finally {
- //释放资源
- if (response != null) {
- response.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- }
- }
- //
- private CloseableHttpClient getHttpClientConnection() {
- //创建默认实例
- CloseableHttpClient httpclient = HttpClients.createDefault();
- //
- // CloseableHttpClient httpClient = HttpClientBuilder.create().build();
- return httpclient;
- }
- //
- private HttpUriRequest getHttpRequest(String url, Map<String, String> map, Map<String, Integer> timeoutMap) {
- int connectTimeout = timeoutMap.get("connectTimeout");
- int requestTimeout = timeoutMap.get("requestTimeout");
- int socketTimeout = timeoutMap.get("socketTimeout");
- // System.out.println("core connectTimeout="+connectTimeout);
- // System.out.println("core requestTimeout="+requestTimeout);
- // System.out.println("core socketTimeout="+socketTimeout);
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- Set<Map.Entry<String, String>> entrySet = map.entrySet();
- for (Map.Entry<String, String> e : entrySet) {
- String name = e.getKey();
- String value = e.getValue();
- NameValuePair pair = new BasicNameValuePair(name, value);
- params.add(pair);
- }
- //
- RequestConfig requestConfig = RequestConfig.custom()
- .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout)
- .setSocketTimeout(socketTimeout).build();
- HttpUriRequest httpGet = RequestBuilder.get().setUri(url)
- .addParameters(params.toArray(new BasicNameValuePair[params.size()]))
- .setConfig(requestConfig).build();
- return httpGet;
- }
- //
- private HttpGet getHttpRequest(String url, Map<String, Integer> timeoutMap) {
- int connectTimeout = timeoutMap.get("connectTimeout");
- int requestTimeout = timeoutMap.get("requestTimeout");
- int socketTimeout = timeoutMap.get("socketTimeout");
- HttpGet httpGet = new HttpGet(url);
- //设置超时时间
- RequestConfig requestConfig = RequestConfig.custom()
- .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout)
- .setSocketTimeout(socketTimeout).build();
- httpGet.setConfig(requestConfig);
- return httpGet;
- }
- //test
- private void get() {
- // CloseableHttpClient httpclient = HttpClients.createDefault();
- // try {
- // // 创建httpget.
- // HttpGet httpget = new HttpGet(httpIp + "/token/getToken?userId=20210501×tamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c");
- // System.out.println("executing request " + httpget.getURI());
- // // 执行get请求.
- // CloseableHttpResponse response = httpclient.execute(httpget);
- // try {
- // // 获取响应实体
- // HttpEntity entity = response.getEntity();
- // System.out.println("--------------------------------------");
- // // 打印响应状态
- // System.out.println(response.getStatusLine());
- // if (entity != null) {
- // // 打印响应内容长度
- // System.out.println("Response content length: " + entity.getContentLength());
- // // 打印响应内容
- // System.out.println("Response content: " + EntityUtils.toString(entity));
- // }
- // System.out.println("------------------------------------");
- // } finally {
- // response.close();
- // }
- // } catch (ClientProtocolException e) {
- // e.printStackTrace();
- // } catch (ParseException e) {
- // e.printStackTrace();
- // } catch (IOException e) {
- // e.printStackTrace();
- // } finally {
- // // 关闭连接,释放资源
- // try {
- // httpclient.close();
- // } catch (IOException e) {
- // e.printStackTrace();
- // }
- // }
- }
- private void getRequest() throws IOException {
- // //1.打开浏览器
- // CloseableHttpClient httpClient = HttpClients.createDefault();
- // //2.声明get请求
- // HttpGet httpGet = new HttpGet(httpIp + "/token/getToken?userId=20210501×tamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c");
- // //3.发送请求
- // CloseableHttpResponse response = httpClient.execute(httpGet);
- // System.out.println("StatusCode=" + response.getStatusLine().getStatusCode());
- // //4.判断状态码
- // if (response.getStatusLine().getStatusCode() == 200) {
- // HttpEntity entity = response.getEntity();
- // //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
- // String string = EntityUtils.toString(entity, "utf-8");
- // System.out.println(string);
- // }
- // //5.关闭资源
- // response.close();
- // httpClient.close();
- }
- }
|