Apache HttpClient 4.1 - 代理设置

时间:2011-02-10 10:04:03

标签: java proxy apache-commons-httpclient

我正在尝试将一些参数发布到服务器,但我需要设置代理。你可以帮助我将它“设置代理”作为我的代码的一部分吗?

HttpHost proxy = new HttpHost("xx.x.x.xx");

DefaultHttpClient httpclient = new DefaultHttpClient();

httpclient.getParams().setParameter("3128",proxy);


HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();

nvps.add(new BasicNameValuePair("aranan", song));

httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
System.out.println("Request Handled?: " + response.getStatusLine());

in = entity.getContent();

httpclient.getConnectionManager().shutdown();

4 个答案:

答案 0 :(得分:60)

是的我整理了我自己的问题,这一行

httpclient.getParams().setParameter("3128",proxy);

应该是

httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);

完整的Apache HttpClient 4.1示例,设置代理可以在下面找到

HttpHost proxy = new HttpHost("ip address",port number);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);

HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("param name", param));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
HttpResponse response = httpclient.execute(httpost);

HttpEntity entity = response.getEntity();
System.out.println("Request Handled?: " + response.getStatusLine());
InputStream in = entity.getContent();
httpclient.getConnectionManager().shutdown();

答案 1 :(得分:41)

非弃用的方式(也在4.5.5版本中)是:

HttpHost proxy = new HttpHost("proxy.com", 80, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
                    .setRoutePlanner(routePlanner)
                    .build();

答案 2 :(得分:4)

当我使用apache httpclient v4.5.5时,我发现在v4.3中不推荐使用HttpClient.getParams(),我们应该使用org.apache.http.client.config.RequestConfig代替。 Code sample 表明:

 HttpHost target = new HttpHost("httpbin.org", 443, "https");
 HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

 RequestConfig config = RequestConfig.custom()
     .setProxy(proxy)
     .build();
 HttpGet request = new HttpGet("/");
 request.setConfig(config);
 CloseableHttpResponse response = httpclient.execute(target, request);

答案 3 :(得分:4)

这是我用来设置代理的快速方法:

import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;    
...
HttpHost proxy = new HttpHost("www.proxy.com", 8080, "http");
HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();