Apache HttpClient 4.1 - Proxy Settings

2022-09-01 07:56:20

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

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();

答案 1

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

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();

答案 2

未弃用的方法(也在4.5.5版本中)是:

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

推荐