web-dev-qa-db-ja.com

Apache HttpClient 4.1-プロキシ設定

POSTサーバーにいくつかのパラメータを設定しようとしていますが、プロキシを設定する必要があります。コードの「プロキシの設定」部分をソートするのを手伝ってもらえますか?

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

はい、この行を自分の問題を整理しました

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

非推奨ではない方法(バージョン4.5.5でも同様):

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

これは、プロキシを設定するための簡単な方法です。

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();
6
Iwo Kucharski

Apache httpclient v4.5.5を使用すると、v4.3でHttpClient.getParams()が非推奨になりました。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);
4
Allen