31

我正在尝试将一些参数发布到服务器,但我需要设置代理。你能帮我对我的代码的“设置代理”部分进行排序吗?

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

4 回答 4

67

是的,我解决了我自己的问题,这条线

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();
于 2011-02-10T12:34:44.350 回答
56

不推荐使用的方法(也在 4.5.5 版本中)是:

HttpHost proxy = new HttpHost("proxy.com", 80, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
                    .setRoutePlanner(routePlanner)
                    .build();
于 2015-07-20T16:15:11.627 回答
8

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

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();
于 2018-07-25T13:13:26.757 回答
6

当我使用 apache httpclient v4.5.5 时,我发现 HttpClient.getParams() 在 v4.3 中已弃用,我们应该org.apache.http.client.config.RequestConfig改用。 代码示例 显示:

 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);
于 2018-03-27T01:36:56.657 回答