http请求

心已赠人 2022-01-15 01:23 401阅读 0赞

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

@SuppressWarnings(“deprecation”)
public class HttpUtil {

  1. //注册端口
  2. //private static int port = 443;
  3. //超时时间(毫秒)
  4. private final static int CONNECTION\_TIME\_OUT = 10000;
  5. public static final int READDATA\_TIMEOUT = 10000;// 数据读取等待超时
  6. protected static Log log = LogFactory.getLog(HttpUtil.class);
  7. public synchronized static String sendDataByGet(String url,
  8. Map<String, String> params, boolean enableProxy, int timeout) \{
  9. if (params != null && params.size() > 0) \{
  10. StringBuffer sb = new StringBuffer();
  11. Set<Entry<String, String>> set = params.entrySet();
  12. for (Iterator<Entry<String, String>> iterator = set.iterator(); iterator.hasNext(); ) \{
  13. Entry<String, String> entry = (Entry<String, String>) iterator.next();
  14. sb.append("&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue()));
  15. \}
  16. if (url.indexOf("?") == -1) \{
  17. sb.deleteCharAt(0);
  18. url = url + "?" + sb.toString();
  19. \} else \{
  20. url = url + sb.toString();
  21. \}
  22. \}
  23. DefaultHttpClient client = null;
  24. if (client == null) \{
  25. client = createHttpClient(timeout);
  26. \}
  27. if (enableProxy) \{
  28. HttpHost host = new HttpHost("10.37.84.16", 80);
  29. client.getParams().setParameter(ConnRoutePNames.DEFAULT\_PROXY, host);
  30. client.getCredentialsProvider().setCredentials(new AuthScope("10.37.84.16", 80), new UsernamePasswordCredentials("um", "密码"));
  31. \}
  32. HttpGet get = new HttpGet(url);
  33. HttpResponse resp = null;
  34. String result = null;
  35. try \{
  36. resp = client.execute(get);
  37. if (resp.getStatusLine().getStatusCode() == HttpStatus.SC\_OK
  38. || resp.getStatusLine().getStatusCode() == 400) \{
  39. result = EntityUtils.toString(resp.getEntity(), HTTP.UTF\_8);
  40. System.out.println(result);
  41. \}
  42. \} catch (UnsupportedEncodingException e) \{
  43. e.printStackTrace();
  44. \} catch (ClientProtocolException e) \{
  45. e.printStackTrace();
  46. \} catch (IOException e) \{
  47. e.printStackTrace();
  48. \} catch (Exception e) \{
  49. e.printStackTrace();
  50. \}
  51. return result;
  52. \}
  53. public synchronized static String sendDataByPost(String url,
  54. List<NameValuePair> datas, boolean enableProxy, int timeout) \{
  55. DefaultHttpClient client = null;
  56. if (client == null) \{
  57. client = createHttpClient(timeout);
  58. \}
  59. if (enableProxy) \{
  60. HttpHost host = new HttpHost("10.37.84.16", 80);
  61. client.getParams().setParameter(ConnRoutePNames.DEFAULT\_PROXY, host);
  62. client.getCredentialsProvider().setCredentials(new AuthScope("10.37.84.16", 80), new UsernamePasswordCredentials("gengqian499", "gq1234!@\#$"));
  63. \}
  64. HttpPost post = new HttpPost(url);
  65. HttpResponse resp = null;
  66. String result = null;
  67. try \{
  68. post.setEntity(new UrlEncodedFormEntity(datas, HTTP.UTF\_8));
  69. resp = client.execute(post);
  70. if (resp.getStatusLine().getStatusCode() == HttpStatus.SC\_OK
  71. || resp.getStatusLine().getStatusCode() == 400) \{
  72. result = EntityUtils.toString(resp.getEntity(), HTTP.UTF\_8);
  73. System.out.println(result);
  74. \}
  75. \} catch (UnsupportedEncodingException e) \{
  76. e.printStackTrace();
  77. \} catch (ClientProtocolException e) \{
  78. e.printStackTrace();
  79. \} catch (IOException e) \{
  80. e.printStackTrace();
  81. \} catch (Exception e) \{
  82. e.printStackTrace();
  83. \}
  84. return result;
  85. \}
  86. public static String doGet(String url) throws IOException \{
  87. CloseableHttpClient httpClient = HttpClients.createDefault();
  88. HttpGet httpGet = new HttpGet(url);
  89. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CONNECTION\_TIME\_OUT).setConnectTimeout(CONNECTION\_TIME\_OUT).build();
  90. httpGet.setConfig(requestConfig);
  91. try \{
  92. HttpResponse resp = httpClient.execute(httpGet);
  93. String result = EntityUtils.toString(resp.getEntity(), HTTP.UTF\_8);
  94. int statusCode = resp.getStatusLine().getStatusCode();
  95. if (statusCode == HttpStatus.SC\_OK) \{
  96. return result;
  97. \} else \{
  98. throw new HttpException("Unsuccessful request --------> The response is statusCode= " + statusCode + " and message= " + result);
  99. \}
  100. \} finally \{
  101. httpClient.close();
  102. \}
  103. \}
  104. private static DefaultHttpClient createHttpClient(int soTimeout) \{
  105. if (soTimeout == 0) \{
  106. soTimeout = CONNECTION\_TIME\_OUT;
  107. \}
  108. try \{
  109. HttpParams params = new BasicHttpParams();
  110. HttpProtocolParams.setVersion(params, HttpVersion.HTTP\_1\_1);
  111. HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT\_CONTENT\_CHARSET);
  112. HttpProtocolParams.setUseExpectContinue(params, true);
  113. // 设置超时时间
  114. params.setParameter(CoreConnectionPNames.CONNECTION\_TIMEOUT, soTimeout);
  115. // 读取超时
  116. params.setParameter(CoreConnectionPNames.SO\_TIMEOUT, soTimeout);
  117. params.setParameter("Connection", "Keep-Alive");
  118. params.setParameter("Content-Length", " 12");
  119. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  120. trustStore.load(null, null);
  121. MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  122. sf.setHostnameVerifier(MySSLSocketFactory.ALLOW\_ALL\_HOSTNAME\_VERIFIER);
  123. SchemeRegistry registry = new SchemeRegistry();
  124. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  125. registry.register(new Scheme("https", sf, 443));
  126. ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, registry);
  127. return new DefaultHttpClient(conMgr, params);
  128. \} catch (Exception e) \{
  129. e.printStackTrace();
  130. return null;
  131. \}
  132. \}
  133. public static String sendHttpsPost(String url, String requestBody, String contentType, String hostName) throws Exception \{
  134. log.info("httpsClient访问开始..." + url);
  135. CloseableHttpClient httpClient = null;
  136. try \{
  137. SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() \{
  138. // 默认信任所有证书
  139. public boolean isTrusted(X509Certificate\[\] arg0, String arg1) \{
  140. return false;
  141. \}
  142. \}).build();
  143. SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW\_ALL\_HOSTNAME\_VERIFIER);
  144. httpClient = HttpClients.custom().setSSLSocketFactory(ssf).build();
  145. HttpPost httpPost = new HttpPost(url);
  146. Authenticator.setDefault(new MyAuthenticator("gaowei399","741asd\#fg"));
  147. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION\_TIME\_OUT).setSocketTimeout(READDATA\_TIMEOUT)
  148. .setProxy(new HttpHost("10.37.84.36", 8080))
  149. .build();
  150. httpPost.setConfig(requestConfig);
  151. httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));
  152. if (StringUtils.isNotBlank(hostName)) \{
  153. httpPost.setHeader("HOST", hostName);
  154. \}
  155. if (StringUtils.isNotBlank(contentType)) \{
  156. httpPost.setHeader("Content-Type", contentType);
  157. \}
  158. HttpResponse resp = httpClient.execute(httpPost);
  159. String result = EntityUtils.toString(resp.getEntity(), HTTP.UTF\_8);
  160. int statusCode = resp.getStatusLine().getStatusCode();
  161. if (statusCode == HttpStatus.SC\_OK) \{
  162. return result;
  163. \} else \{
  164. throw new HttpException("HTTP REQUEST FAIL ---- statusCode: " + statusCode + " and result: " + result);
  165. \}
  166. \} catch (Exception e) \{
  167. log.error(e.getMessage(), e);
  168. throw new RuntimeException("通讯未知系统异常", e);
  169. \} finally \{
  170. if (httpClient != null) \{
  171. httpClient.close();
  172. \}
  173. \}
  174. \}

}

/**
* 过滤证书
*
*/
@SuppressWarnings(“deprecation”)
class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance(“TLS”);

  1. public MySSLSocketFactory(KeyStore truststore)
  2. throws NoSuchAlgorithmException, KeyManagementException,
  3. KeyStoreException, UnrecoverableKeyException \{
  4. super(truststore);
  5. TrustManager tm = new X509TrustManager() \{
  6. public void checkClientTrusted(X509Certificate\[\] chain,
  7. String authType) throws CertificateException \{
  8. \}
  9. public void checkServerTrusted(X509Certificate\[\] chain,
  10. String authType) throws CertificateException \{
  11. \}
  12. public X509Certificate\[\] getAcceptedIssuers() \{
  13. return null;
  14. \}
  15. \};
  16. sslContext.init(null, new TrustManager\[\]\{tm\}, null);
  17. \}
  18. [@Override][Override]
  19. public Socket createSocket(Socket socket, String host, int port,
  20. boolean autoClose) throws IOException, UnknownHostException \{
  21. return sslContext.getSocketFactory().createSocket(socket, host, port,
  22. autoClose);
  23. \}
  24. [@Override][Override]
  25. public Socket createSocket() throws IOException \{
  26. return sslContext.getSocketFactory().createSocket();
  27. \}

}

转载于:https://my.oschina.net/u/198077/blog/3047633

发表评论

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

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

相关阅读

    相关 HTTP请求

    http请求分为请求头和请求体,请求头的第一行又为请求行,下面分别进行介绍。 请求头 话不多说,我们直接以一个请求头为例子来介绍,我们随便抓取一个包进行演示,下列是我抓

    相关 http请求

    http 1、是客服端与服务器传输文本的一种协议 2、http协议是无状态的 3、http协议默认端口是80 4、http协议(加密传输)端口是443