http请求 心已赠人 2022-01-15 01:23 376阅读 0赞 [2019独角兽企业重金招聘Python工程师标准>>> ][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 \{ //注册端口 //private static int port = 443; //超时时间(毫秒) private final static int CONNECTION\_TIME\_OUT = 10000; public static final int READDATA\_TIMEOUT = 10000;// 数据读取等待超时 protected static Log log = LogFactory.getLog(HttpUtil.class); public synchronized static String sendDataByGet(String url, Map<String, String> params, boolean enableProxy, int timeout) \{ if (params != null && params.size() > 0) \{ StringBuffer sb = new StringBuffer(); Set<Entry<String, String>> set = params.entrySet(); for (Iterator<Entry<String, String>> iterator = set.iterator(); iterator.hasNext(); ) \{ Entry<String, String> entry = (Entry<String, String>) iterator.next(); sb.append("&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue())); \} if (url.indexOf("?") == -1) \{ sb.deleteCharAt(0); url = url + "?" + sb.toString(); \} else \{ url = url + sb.toString(); \} \} DefaultHttpClient client = null; if (client == null) \{ client = createHttpClient(timeout); \} if (enableProxy) \{ HttpHost host = new HttpHost("10.37.84.16", 80); client.getParams().setParameter(ConnRoutePNames.DEFAULT\_PROXY, host); client.getCredentialsProvider().setCredentials(new AuthScope("10.37.84.16", 80), new UsernamePasswordCredentials("um", "密码")); \} HttpGet get = new HttpGet(url); HttpResponse resp = null; String result = null; try \{ resp = client.execute(get); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC\_OK || resp.getStatusLine().getStatusCode() == 400) \{ result = EntityUtils.toString(resp.getEntity(), HTTP.UTF\_8); System.out.println(result); \} \} catch (UnsupportedEncodingException e) \{ e.printStackTrace(); \} catch (ClientProtocolException e) \{ e.printStackTrace(); \} catch (IOException e) \{ e.printStackTrace(); \} catch (Exception e) \{ e.printStackTrace(); \} return result; \} public synchronized static String sendDataByPost(String url, List<NameValuePair> datas, boolean enableProxy, int timeout) \{ DefaultHttpClient client = null; if (client == null) \{ client = createHttpClient(timeout); \} if (enableProxy) \{ HttpHost host = new HttpHost("10.37.84.16", 80); client.getParams().setParameter(ConnRoutePNames.DEFAULT\_PROXY, host); client.getCredentialsProvider().setCredentials(new AuthScope("10.37.84.16", 80), new UsernamePasswordCredentials("gengqian499", "gq1234!@\#$")); \} HttpPost post = new HttpPost(url); HttpResponse resp = null; String result = null; try \{ post.setEntity(new UrlEncodedFormEntity(datas, HTTP.UTF\_8)); resp = client.execute(post); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC\_OK || resp.getStatusLine().getStatusCode() == 400) \{ result = EntityUtils.toString(resp.getEntity(), HTTP.UTF\_8); System.out.println(result); \} \} catch (UnsupportedEncodingException e) \{ e.printStackTrace(); \} catch (ClientProtocolException e) \{ e.printStackTrace(); \} catch (IOException e) \{ e.printStackTrace(); \} catch (Exception e) \{ e.printStackTrace(); \} return result; \} public static String doGet(String url) throws IOException \{ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CONNECTION\_TIME\_OUT).setConnectTimeout(CONNECTION\_TIME\_OUT).build(); httpGet.setConfig(requestConfig); try \{ HttpResponse resp = httpClient.execute(httpGet); String result = EntityUtils.toString(resp.getEntity(), HTTP.UTF\_8); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC\_OK) \{ return result; \} else \{ throw new HttpException("Unsuccessful request --------> The response is statusCode= " + statusCode + " and message= " + result); \} \} finally \{ httpClient.close(); \} \} private static DefaultHttpClient createHttpClient(int soTimeout) \{ if (soTimeout == 0) \{ soTimeout = CONNECTION\_TIME\_OUT; \} try \{ HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP\_1\_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT\_CONTENT\_CHARSET); HttpProtocolParams.setUseExpectContinue(params, true); // 设置超时时间 params.setParameter(CoreConnectionPNames.CONNECTION\_TIMEOUT, soTimeout); // 读取超时 params.setParameter(CoreConnectionPNames.SO\_TIMEOUT, soTimeout); params.setParameter("Connection", "Keep-Alive"); params.setParameter("Content-Length", " 12"); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(MySSLSocketFactory.ALLOW\_ALL\_HOSTNAME\_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(conMgr, params); \} catch (Exception e) \{ e.printStackTrace(); return null; \} \} public static String sendHttpsPost(String url, String requestBody, String contentType, String hostName) throws Exception \{ log.info("httpsClient访问开始..." + url); CloseableHttpClient httpClient = null; try \{ SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() \{ // 默认信任所有证书 public boolean isTrusted(X509Certificate\[\] arg0, String arg1) \{ return false; \} \}).build(); SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW\_ALL\_HOSTNAME\_VERIFIER); httpClient = HttpClients.custom().setSSLSocketFactory(ssf).build(); HttpPost httpPost = new HttpPost(url); Authenticator.setDefault(new MyAuthenticator("gaowei399","741asd\#fg")); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION\_TIME\_OUT).setSocketTimeout(READDATA\_TIMEOUT) .setProxy(new HttpHost("10.37.84.36", 8080)) .build(); httpPost.setConfig(requestConfig); httpPost.setEntity(new StringEntity(requestBody, "UTF-8")); if (StringUtils.isNotBlank(hostName)) \{ httpPost.setHeader("HOST", hostName); \} if (StringUtils.isNotBlank(contentType)) \{ httpPost.setHeader("Content-Type", contentType); \} HttpResponse resp = httpClient.execute(httpPost); String result = EntityUtils.toString(resp.getEntity(), HTTP.UTF\_8); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC\_OK) \{ return result; \} else \{ throw new HttpException("HTTP REQUEST FAIL ---- statusCode: " + statusCode + " and result: " + result); \} \} catch (Exception e) \{ log.error(e.getMessage(), e); throw new RuntimeException("通讯未知系统异常", e); \} finally \{ if (httpClient != null) \{ httpClient.close(); \} \} \} \} /\*\* \* 过滤证书 \* \*/ @SuppressWarnings("deprecation") class MySSLSocketFactory extends SSLSocketFactory \{ SSLContext sslContext = SSLContext.getInstance("TLS"); public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException \{ super(truststore); TrustManager tm = new X509TrustManager() \{ public void checkClientTrusted(X509Certificate\[\] chain, String authType) throws CertificateException \{ \} public void checkServerTrusted(X509Certificate\[\] chain, String authType) throws CertificateException \{ \} public X509Certificate\[\] getAcceptedIssuers() \{ return null; \} \}; sslContext.init(null, new TrustManager\[\]\{tm\}, null); \} [@Override][Override] public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException \{ return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); \} [@Override][Override] public Socket createSocket() throws IOException \{ return sslContext.getSocketFactory().createSocket(); \} \} 转载于:https://my.oschina.net/u/198077/blog/3047633 [2019_Python_]: https://my.oschina.net/u/2663968/blog/3061697 [hot3.png]: /images/20220114/5d7e1658ae0247e785a51b3acc1b08e7.png [Override]: https://my.oschina.net/u/1162528
相关 HTTP请求 http请求分为请求头和请求体,请求头的第一行又为请求行,下面分别进行介绍。 请求头 话不多说,我们直接以一个请求头为例子来介绍,我们随便抓取一个包进行演示,下列是我抓 港控/mmm°/ 2023年10月01日 19:42/ 0 赞/ 53 阅读
相关 http请求 ![1392562-20190731084149017-137668602.png][] ![1392562-20190731085742465-259257336.png] 女爷i/ 2023年08月17日 16:08/ 0 赞/ 179 阅读
相关 http请求 http 1、是客服端与服务器传输文本的一种协议 2、http协议是无状态的 3、http协议默认端口是80 4、http协议(加密传输)端口是443 r囧r小猫/ 2023年03月02日 10:53/ 0 赞/ 39 阅读
相关 http请求 ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ub ゝ一世哀愁。/ 2022年12月24日 04:51/ 0 赞/ 189 阅读
相关 http请求 一、request请求 ![Center][] 二、response响应 ![Center 1][] 附: ![Center 2][] [ 柔情只为你懂/ 2022年07月15日 22:41/ 0 赞/ 253 阅读
相关 网站的Http请求转为Https请求 一、申请Https证书 [https://common-buy.aliyun.com/?spm=5176.2020520163.cas.1.zTLyhO&commodit 痛定思痛。/ 2022年06月12日 01:43/ 0 赞/ 328 阅读
相关 HTTP请求 原生JS写一个GET请求 let xhr = new XMLHttpRequest(); xhr.open("GET", "/list"); xhr. 小鱼儿/ 2022年05月23日 00:13/ 0 赞/ 378 阅读
相关 Http请求 package fun.lovey.http; import java.io.; import java.net.HttpURLConnec 快来打我*/ 2022年04月04日 13:58/ 0 赞/ 414 阅读
相关 http请求 [2019独角兽企业重金招聘Python工程师标准>>> ][2019_Python_] ![hot3.png][] import java.io.\; im 心已赠人/ 2022年01月15日 01:23/ 0 赞/ 377 阅读
相关 HTTPS请求 hhtps:HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer),是以安全为目标的 HTTP通道, ゝ一纸荒年。/ 2021年09月30日 02:42/ 0 赞/ 419 阅读
还没有评论,来说两句吧...