2012-11-09 33 views
0

使用新httocomponent客戶端模塊Httpcomponents客戶端代理問題

當試圖通過代理連接到互聯網,我有問題,如果我直接使用代理對象和HttpURLConnection的一切順利:

URL u = new URL("http://www.google.com"); 
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("somehost", 8080)); 
HttpURLConnection con = (HttpURLConnection) u.openConnection(proxy); 
con.setRequestMethod("GET"); 
System.out.println(con.getResponseCode()); 

現在,我嘗試做相同的新的API:

HttpHost proxy = new HttpHost("somehost", 8080, "http"); 
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 
HttpHost targetHost = new HttpHost("http://www.google.com"); 
HttpGet httpGet = new HttpGet("/"); 
try { 
    HttpResponse httpResponse = httpClient.execute(targetHost, httpGet); 
    System.out.println(httpResponse.toString()); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

,但我得到這個:

HTTP/1.1 407 Proxy Authentication Required (Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied. ) [Via: 1.1 xxx, Proxy-Authenticate: Negotiate, Proxy-Authenticate: Kerberos, Proxy-Authenticate: NTLM, Connection: Keep-Alive, Proxy-Connection: Keep-Alive, Pragma: no-cache, Cache-Control: no-cache, Content-Type: text/html, Content-Length: 7079 ] 

我也試過

ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
httpClient.getConnectionManager().getSchemeRegistry(),new MyProxySelector()); 
    httpClient.setRoutePlanner(routePlanner); 

凡MyProxySelector返回我NNED代理,但沒有結果。

爲什麼使用新API使代碼內部需要代理認證?

回答

0

我不知道爲什麼使用ProxySelectorRoutePlanner的解決方案不起作用,您確定使用代理設置啓動您的JVM嗎?

它看起來像你需要添加此行:

httpClient.getCredentialsProvider().setCredentials(new AuthScope("yourProxyHost", Port), 
      new UsernamePasswordCredentials("yourUsername", "yourPass"));