HttpUtils

Posted daleidedd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpUtils相关的知识,希望对你有一定的参考价值。

1.pom.xml中添加

<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version></dependency>

2.写 HttpClientPool(高并发情况下,为了提高http请求效率,加入http 连接池,减少3次握手次数,提高请求效率)

package com.common.utils.http;import org.apache.http.client.config.CookieSpecs;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;/** * httpclient */public class HttpClientPool { private static PoolingHttpClientConnectionManager connectionManager = null; static{ connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(400); connectionManager.setDefaultMaxPerRoute(50); } public static CloseableHttpClient getHttpClient(){ RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); CloseableHttpClient client = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(globalConfig).build(); return client; }
/** * 配置信息 * @param httpRequestBase */ public static void config(HttpRequestBase httpRequestBase,int ... timeout) { httpRequestBase.setHeader("User-Agent", "Mozilla/5.0"); httpRequestBase.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); httpRequestBase.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");//"en-US,en;q=0.5"); httpRequestBase.setHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7"); int connTimeout = 10000; // 默认10秒 if(timeout.length > 0) { connTimeout = timeout[0] * 1000; }
// 配置请求的超时设置 RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(connTimeout) .setConnectTimeout(connTimeout) .setSocketTimeout(connTimeout) .build(); httpRequestBase.setConfig(requestConfig); }
}


3.HttpUtils调用方法

package com.common.utils.http;

import org.apache.commons.io.IOUtils;import org.apache.http.HttpEntity;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.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;
import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;import java.util.Map;
/** * Http调用方法 */public class HttpUtils { private final static String charset = "UTF-8";
/** * Get请求 * * @param url * @return */ public static String sendGet(String url, int... timeout) { HttpGet httpGet = new HttpGet(url); HttpClientPool.config(httpGet, timeout);
return execute(httpGet); }

/** * Get请求,设置请求头 * * @param url * @return */ public static String sendGet(String url, Map<String, String> header, int... timeout) { HttpGet httpGet = new HttpGet(url); HttpClientPool.config(httpGet, timeout); for (Map.Entry<String, String> entry : header.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); }
return execute(httpGet); }
/** * Post请求 * * @param url * @return */ public static String sendPost(String url, Map<?, ?> param, int... timeout) { // 1、处理参数 List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>(); for (Map.Entry<?, ?> entry : param.entrySet()) { formParams.add(new BasicNameValuePair(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()))); } UrlEncodedFormEntity uefEntity = null; try { uefEntity = new UrlEncodedFormEntity(formParams, charset); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
// 2、准备请求 HttpPost httpPost = new HttpPost(url); httpPost.setEntity(uefEntity); HttpClientPool.config(httpPost, timeout);
return execute(httpPost); }
/** * Post请求 设置请求头 * * @param url * @return */ public static String sendPost(String url, Map<?, ?> param, Map<String, String> header, int... timeout) { // 1、处理参数 List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>(); for (Map.Entry<?, ?> entry : param.entrySet()) { formParams.add(new BasicNameValuePair(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()))); } UrlEncodedFormEntity uefEntity = null; try { uefEntity = new UrlEncodedFormEntity(formParams, charset); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
// 2、准备请求 HttpPost httpPost = new HttpPost(url); httpPost.setEntity(uefEntity); HttpClientPool.config(httpPost, timeout); for (Map.Entry<String, String> entry : header.entrySet()) { httpPost.setHeader(entry.getKey(), entry.getValue()); }
return execute(httpPost); }
/** * Post请求 * * @param url * @return */ public static CloseableHttpResponse sendPostReturnCode(String url, Map<?, ?> param, int... timeout) { // 1、处理参数 List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>(); for (Map.Entry<?, ?> entry : param.entrySet()) { formParams.add(new BasicNameValuePair(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()))); } UrlEncodedFormEntity uefEntity = null; try { uefEntity = new UrlEncodedFormEntity(formParams, charset); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
// 2、准备请求 HttpPost httpPost = new HttpPost(url); httpPost.setEntity(uefEntity); HttpClientPool.config(httpPost, timeout); CloseableHttpResponse response = null; try { response = HttpClientPool.getHttpClient().execute(httpPost); } catch (IOException e) { e.printStackTrace(); } return response; }

/** * Post请求,请求头参数 * @param url * @return */ public static String sendPostHeaderParams(String url, Map<?, ?> param, int... timeout) { // 1、处理参数 HttpPost httpPost = new HttpPost(url); for (Map.Entry<?, ?> entry : param.entrySet()) { httpPost.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); }
// 2、准备请求 HttpClientPool.config(httpPost, timeout);
return execute(httpPost); }
/** * 执行请求 * * @param httpRequestBase * @return */ private static String execute(HttpRequestBase httpRequestBase) { CloseableHttpResponse response = null; String result = null; try { // 方式请求 response = HttpClientPool.getHttpClient().execute(httpRequestBase); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity, charset); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(response); } return result; }
/** * 发送post请求 * * @param url 发送请求的 URL * @param jsonData 请求参数,原生的JSON 字符串。 * @param timeout 超时时间,单位秒 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String jsonData, int... timeout) { int connTimeout = 10000; // 默认10秒 if (timeout.length > 0) { connTimeout = timeout[0] * 1000; }
String data = jsonData; String response = null; try { CloseableHttpClient httpclient = null; CloseableHttpResponse httpresponse = null; try { httpclient = HttpClientPool.getHttpClient(); HttpPost httppost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(connTimeout).setConnectionRequestTimeout(connTimeout) .setSocketTimeout(connTimeout).build(); httppost.setConfig(requestConfig); StringEntity stringentity = new StringEntity(data, ContentType.create("application/json", charset)); httppost.setEntity(stringentity); httpresponse = httpclient.execute(httppost); response = EntityUtils .toString(httpresponse.getEntity());
} catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(httpresponse); }
} catch (Exception e) { e.printStackTrace(); } return response; }
/** * Get请求,抛出异常 * * @param url * @return */ public static String sendHttpGet(String url, int... timeout) throws IOException { HttpGet httpGet = new HttpGet(url); HttpClientPool.config(httpGet, timeout); CloseableHttpResponse response = null; String result = null; response = HttpClientPool.getHttpClient().execute(httpGet); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity, charset); IOUtils.closeQuietly(response); return result; }
}


4.发送端测试代码

    4.1 Get请求

private static final String URL = "http://10.0.51.114:8066/yangguo";
@RequestMapping("/aa")public String testHttp() { String s = HttpUtils.sendGet(URL, 90); return s;}

    4.2 Post请求

private static final String CC = "http://10.0.51.114:8066/cc";
@RequestMapping("/cc")public String cc() { Map<String, String> map = new HashMap<>(); map.put("a", "疫情"); map.put("b", "早点过去"); String s = HttpUtils.sendPost(CC, map, 60); return s;}

5.接受方测试代码:

    5.1对应的是4.1

@RequestMapping("/yangguo")    public String yangguo() { System.out.println("测试通过"); return "测试通过";}

    5.2对应的是4.2

@RequestMapping("/cc")public String cc(@RequestParam(value = "a", required = false) String a, @RequestParam(value = "b", required = false) String b) { System.out.println(a); System.out.println(b); return a + b;}

注:项目用有些方法需要根据业务来封装,这里只是例子.

以上是关于HttpUtils的主要内容,如果未能解决你的问题,请参考以下文章

httpUtils python

XML_解析 ——HttpUtils

python接口自动化httpUtils

使用Xutils(HttpUtils)请求网络数据

android-----XUtils框架之HttpUtils源码分析

HttpUtils