尝试使用新的httocomponent-client模块通过代理连接到互联网时遇到问题
如果我直接使用Proxy对象和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返回我已找到但没有结果的代理。
为什么使用新API会在代码中进行代理身份验证?
答案 0 :(得分:0)
我不知道为什么使用ProxySelectorRoutePlanner的解决方案不起作用,您确定使用代理设置启动JVM吗?
看起来你需要添加这一行:
httpClient.getCredentialsProvider().setCredentials(new AuthScope("yourProxyHost", Port),
new UsernamePasswordCredentials("yourUsername", "yourPass"));