http使用代理
直接上代码:
HttpUrlConnection使用代理:
private static HttpURLConnection getConnection(URL url, String method, String ctype) throws IOException { HttpURLConnection conn; if (hasProxy) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); conn = (HttpURLConnection)url.openConnection(proxy); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod(method); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Connection", "Keep-Alive"); return conn; }
https:
private static HttpsURLConnection getConnectionHttps(URL url, String method, String ctype) throws IOException { SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); // 或SSL X509TrustManager[] xtmArray = new X509TrustManager[]{new myX509TrustManager()}; sslContext.init(null, xtmArray, new java.security.SecureRandom()); } catch (GeneralSecurityException e) { e.printStackTrace(); } if (sslContext != null) { HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } HttpsURLConnection.setDefaultHostnameVerifier(new myHostnameVerifier()); HttpsURLConnection conn; if (hasProxy) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); conn = (HttpsURLConnection)url.openConnection(proxy); } else { conn = (HttpsURLConnection) url.openConnection(); } conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod(method); conn.setRequestProperty("Content-Type", ctype); conn.setRequestProperty("Connection", "Keep-Alive"); return conn; }
httpClent:
RequestConfig requestConfig = null; if(StringUtil.isEmpty(proxyHost)){ requestConfig = RequestConfig.custom() .setSocketTimeout(connectTimeout) .setConnectTimeout(connectTimeout) .build(); }else{ //代理 HttpHost proxy = new HttpHost(proxyHost,proxyPort); requestConfig = RequestConfig.custom() .setProxy(proxy) .setSocketTimeout(connectTimeout) .setConnectTimeout(connectTimeout) .build(); }
共同代码:
private static String proxyHost; private static int proxyPort; private static boolean hasProxy = false; public void setProxy(String proxyHost,int proxyPort) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; hasProxy = true; }