2017-10-20 116 views
0

我写了一个JAVA爬虫,并尝试使用proxy并忽略任何https certificationInternalHttpClient.getParams()与UnsupportedOperationException

但它不工作与

java.lang.UnsupportedOperationException (在org.apache.http.impl.client.InternalHttpClient.getParams)

我搜索的解决方案,主要是说我的HttpClient的版本很旧,但是我从apache网站更新到最新版本,这个异常仍然发生。

其后的代码是我的履带代码:

public static void main(String[] args) { 
    try{ 
     TrustManager[] trustAllCerts = new TrustManager[] { 
      new X509TrustManager() { 
       public X509Certificate[] getAcceptedIssuers() { 
         return null; 
        } 
       public void checkClientTrusted(X509Certificate[] certs, String authType) {} 
       public void checkServerTrusted(X509Certificate[] certs, String authType) {} 
       } 
     }; 
     SSLContext ctx = SSLContext.getInstance("TLS"); 
     ctx.init(null, trustAllCerts, null); 
     LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx); 
     CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();    
     HttpHost proxy = new HttpHost("127.0.0.1", 8888,"http"); 
     client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy); 
     HttpGet request = new HttpGet("https://www.javaworld.com.tw/jute/post/view?bid=29&id=312144"); 
     CloseableHttpResponse response = client.execute(request); 
     String entity = EntityUtils.toString(response.getEntity(), "utf-8"); 
     System.out.println(entity); 
    }catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

非常感谢任何解决方案。

回答

0

我有同样的问题,这是因为该方法已被弃用,并在最新版本中不可用。

我尝试下面的代码和它的工作对我来说

 public static HttpClient createClient() { 
     try { 
      SSLContextBuilder builder = new SSLContextBuilder(); 
      builder.useProtocol("TLSv1.2"); 
      builder.loadTrustMaterial(null, new TrustStrategy() { 
       @Override 
       public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
        return true; 
       } 
      }); 
      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        builder.build()); 

      HttpClientBuilder hcBuilder = HttpClients.custom(); 
      HttpHost httpProxy = new HttpHost(bundle.getString("PROXY_HOST"), Integer.parseInt(bundle.getString("PROXY_PORT"))); 
      DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(httpProxy); 
      hcBuilder.setRoutePlanner(routePlanner); 

      CloseableHttpClient httpclient = hcBuilder 
        .setSSLSocketFactory(sslsf).build(); 

      return httpclient; 
     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 
    } 
+0

感谢您的解决方案。不好意思,新的SSLConnectionSocketFactory( builder.build())和bundle.getString(“PROXY_HOST”)的'bundle'是什么意思? – Akira

+0

我已更新代码以包含完整的方法。这应该有所帮助。 – Clement

相关问题