Java 使用HttpClient进行模拟请求

阳光穿透心脏的1/2处 2021-09-27 06:30 709阅读 0赞

一、 环境

jdk版本: jdk1.8+

HttpClient版本: httpClient4.5+

推荐一个Java学习的网站 : http://how2j.cn?p=17361

二、 下载jar包

1、 下载HttpClient的jar包,在apache官网

  1. **下载地址**: [http://hc.apache.org/downloads.cgi][http_hc.apache.org_downloads.cgi]

三、 使用步骤(转)

  1. 创建HttpClient对象,HttpClients.createDefault()。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象,HttpPost httpPost = new HttpPost(url)。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。List valuePairs = new LinkedList();valuePairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));httpPost.setEntity(formEntity)。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  6. 释放连接。无论执行方法是否成功,都必须释放连接

    HttpClient在4.3版本以后声明HttpClient的方法和以前略有区别,不再是直接声明new DefaultHttpClient() .

四、 代码示例

  1. package util;
  2. import org.apache.http.*;
  3. import org.apache.http.client.ClientProtocolException;
  4. import org.apache.http.client.CookieStore;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.config.CookieSpecs;
  7. import org.apache.http.client.config.RequestConfig;
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;
  9. import org.apache.http.client.methods.CloseableHttpResponse;
  10. import org.apache.http.client.methods.HttpGet;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.client.protocol.HttpClientContext;
  13. import org.apache.http.config.Registry;
  14. import org.apache.http.config.RegistryBuilder;
  15. import org.apache.http.conn.socket.ConnectionSocketFactory;
  16. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  17. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  18. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  19. import org.apache.http.cookie.Cookie;
  20. import org.apache.http.impl.client.BasicCookieStore;
  21. import org.apache.http.impl.client.CloseableHttpClient;
  22. import org.apache.http.impl.client.HttpClientBuilder;
  23. import org.apache.http.impl.client.HttpClients;
  24. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  25. import org.apache.http.message.BasicHeader;
  26. import org.apache.http.message.BasicNameValuePair;
  27. import org.apache.http.ssl.SSLContextBuilder;
  28. import org.apache.http.ssl.TrustStrategy;
  29. import org.apache.http.util.EntityUtils;
  30. import javax.net.ssl.SSLContext;
  31. import javax.net.ssl.TrustManager;
  32. import javax.net.ssl.X509TrustManager;
  33. import java.io.*;
  34. import java.security.KeyManagementException;
  35. import java.security.KeyStoreException;
  36. import java.security.NoSuchAlgorithmException;
  37. import java.security.cert.CertificateException;
  38. import java.security.cert.X509Certificate;
  39. import java.util.ArrayList;
  40. import java.util.HashMap;
  41. import java.util.List;
  42. import java.util.Map;
  43. import java.util.concurrent.TimeUnit;
  44. /**
  45. * 模拟请求工具类
  46. */
  47. public class HttpUtil {
  48. /**
  49. * http get请求
  50. *
  51. * @param url
  52. * @return
  53. */
  54. public static String httpGet(String url) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
  55. return httpGet(url, null, false);
  56. }
  57. /**、
  58. * https get 请求
  59. * @param url
  60. * @return
  61. * @throws ClassNotFoundException
  62. * @throws KeyManagementException
  63. * @throws NoSuchAlgorithmException
  64. * @throws KeyStoreException
  65. * @throws IOException
  66. */
  67. public static String httpsGet(String url) throws ClassNotFoundException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException {
  68. return httpGet(url, null, true);
  69. }
  70. /**
  71. * http post 请求
  72. * @param url
  73. * @param params
  74. * @return
  75. * @throws NoSuchAlgorithmException
  76. * @throws KeyStoreException
  77. * @throws KeyManagementException
  78. */
  79. public static String httpPost(String url, HashMap<String, String> params) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
  80. return httpPost(url, params, null, false);
  81. }
  82. /**
  83. * https post 请求
  84. * @param url
  85. * @param params
  86. * @return
  87. * @throws NoSuchAlgorithmException
  88. * @throws KeyStoreException
  89. * @throws KeyManagementException
  90. */
  91. public static String httpsPost(String url, HashMap<String, String> params) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
  92. return httpPost(url, params, null, true);
  93. }
  94. /**
  95. * @param @return 参数
  96. * @return String 返回类型
  97. * @throws
  98. * @Title: httpGet
  99. * @Description: TODO(http get请求)
  100. */
  101. public static String httpGet(String url, HashMap<String, Object> maps, boolean https) throws IOException, ClassNotFoundException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
  102. // 创建HttpClient上下文
  103. HttpClientContext context = HttpClientContext.create();
  104. // 创建一个CloseableHttpClient
  105. CloseableHttpClient httpClient = null;
  106. if(https){
  107. httpClient = getCloseableHttpClient();
  108. }else{
  109. httpClient = HttpClients.createDefault();
  110. }
  111. // get method
  112. HttpGet httpGet = new HttpGet(url);
  113. //设置header
  114. if (maps != null) {
  115. if (maps.containsKey(HttpHeaders.REFERER)) {
  116. httpGet.setHeader(HttpHeaders.REFERER, (String) maps.get(HttpHeaders.REFERER));
  117. }
  118. if (maps.containsKey(HttpHeaders.HOST)) {
  119. httpGet.setHeader(HttpHeaders.HOST, (String) maps.get(HttpHeaders.HOST));
  120. }
  121. if (maps.containsKey(HttpHeaders.USER_AGENT)) {
  122. httpGet.setHeader(HttpHeaders.USER_AGENT, (String) maps.get(HttpHeaders.USER_AGENT));
  123. }
  124. if (maps.containsKey(HttpHeaders.ACCEPT)) {
  125. httpGet.setHeader(HttpHeaders.ACCEPT, (String) maps.get(HttpHeaders.ACCEPT));
  126. }
  127. }
  128. //response
  129. CloseableHttpResponse response = null;
  130. //get response into String
  131. String result = "";
  132. response = httpClient.execute(httpGet, context);
  133. HttpEntity entity = response.getEntity();
  134. result = EntityUtils.toString(entity, "UTF-8");
  135. //释放连接
  136. httpGet.releaseConnection();
  137. httpClient.close();
  138. return result;
  139. }
  140. /**
  141. * 创建CloseableHttpClient
  142. * @return
  143. * @throws KeyStoreException
  144. * @throws NoSuchAlgorithmException
  145. * @throws KeyManagementException
  146. */
  147. private static CloseableHttpClient getCloseableHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
  148. // 全局请求设置
  149. RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(10000).build();
  150. //SSL 过滤
  151. SSLContextBuilder builder = new SSLContextBuilder();
  152. builder.loadTrustMaterial(null, new TrustStrategy() {
  153. public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  154. return true;
  155. }
  156. });
  157. SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
  158. Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", trustAllHttpsCertificates()).build();
  159. PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry);
  160. manager.setMaxTotal(200);
  161. // http 请求默认设置
  162. HttpClientBuilder custom = HttpClients.custom();
  163. custom.setDefaultRequestConfig(globalConfig);
  164. custom.setSSLSocketFactory(sslConnectionSocketFactory);
  165. custom.setConnectionManager(manager);
  166. custom.setConnectionManagerShared(true);
  167. return custom.build();
  168. }
  169. /**
  170. * SSL https 构建
  171. * @return
  172. */
  173. private static SSLConnectionSocketFactory trustAllHttpsCertificates() {
  174. SSLConnectionSocketFactory socketFactory = null;
  175. TrustManager[] trustAllCerts = new TrustManager[1];
  176. TrustManager tm = new miTM();
  177. trustAllCerts[0] = tm;
  178. SSLContext sc = null;
  179. try {
  180. sc = SSLContext.getInstance("TLS");//sc = SSLContext.getInstance("TLS")
  181. sc.init(null, trustAllCerts, null);
  182. socketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
  183. //HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  184. } catch (NoSuchAlgorithmException e) {
  185. e.printStackTrace();
  186. } catch (KeyManagementException e) {
  187. e.printStackTrace();
  188. }
  189. return socketFactory;
  190. }
  191. static class miTM implements TrustManager, X509TrustManager {
  192. public X509Certificate[] getAcceptedIssuers() {
  193. return null;
  194. }
  195. public void checkServerTrusted(X509Certificate[] certs, String authType) {
  196. //don't check
  197. }
  198. public void checkClientTrusted(X509Certificate[] certs, String authType) {
  199. //don't check
  200. }
  201. }
  202. /**
  203. * @param @return 参数
  204. * @return String 返回类型
  205. * @throws
  206. * @Title: httpPost
  207. * @Description: TODO(http post请求)
  208. */
  209. public static String httpPost(String url, HashMap<String, String> params, HashMap<String, Object> config, boolean https) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
  210. //httpClient
  211. //HttpClient httpClient = getCloseableHttpClient();
  212. HttpClient httpClient = null;
  213. if(https){
  214. httpClient = getCloseableHttpClient();
  215. }else{
  216. httpClient = HttpClients.createDefault();
  217. }
  218. // get method
  219. HttpPost httpPost = new HttpPost(url);
  220. //设置header
  221. if (config != null) {
  222. if (config.containsKey(HttpHeaders.REFERER)) {
  223. httpPost.setHeader(HttpHeaders.REFERER, (String) config.get(HttpHeaders.REFERER));
  224. }
  225. if (config.containsKey(HttpHeaders.HOST)) {
  226. httpPost.setHeader(HttpHeaders.HOST, (String) config.get(HttpHeaders.HOST));
  227. }
  228. if (config.containsKey(HttpHeaders.USER_AGENT)) {
  229. httpPost.setHeader(HttpHeaders.USER_AGENT, (String) config.get(HttpHeaders.USER_AGENT));
  230. }
  231. if (config.containsKey(HttpHeaders.ACCEPT)) {
  232. httpPost.setHeader(HttpHeaders.ACCEPT, (String) config.get(HttpHeaders.ACCEPT));
  233. }
  234. if(config.containsKey(HttpHeaders.CONTENT_TYPE)){
  235. httpPost.setHeader(HttpHeaders.CONTENT_TYPE, (String) config.get(HttpHeaders.CONTENT_TYPE));
  236. }
  237. if(config.containsKey("Origin")){
  238. httpPost.setHeader("Origin", (String) config.get("Origin"));
  239. }
  240. }
  241. //set params post参数
  242. List<NameValuePair> listParams = new ArrayList<NameValuePair>();
  243. //添加post参数
  244. for (Map.Entry<String, String> entry : params.entrySet()) {
  245. listParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  246. }
  247. String result = "";
  248. try {
  249. //response
  250. httpPost.setEntity(new UrlEncodedFormEntity(listParams, "UTF-8"));
  251. HttpResponse response = null;
  252. response = httpClient.execute(httpPost);
  253. //get response into String
  254. HttpEntity entity = response.getEntity();
  255. result = EntityUtils.toString(entity, "UTF-8");
  256. } catch (UnsupportedEncodingException e) {
  257. e.printStackTrace();
  258. } catch (ClientProtocolException e) {
  259. e.printStackTrace();
  260. } catch (IOException e) {
  261. e.printStackTrace();
  262. }finally {
  263. httpPost.releaseConnection();
  264. ((CloseableHttpClient) httpClient).close();
  265. }
  266. return result;
  267. }
  268. }

发表评论

表情:
评论列表 (有 0 条评论,709人围观)

还没有评论,来说两句吧...

相关阅读