Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache HttpClient 4.1 - Proxy Settings

I am trying to POST some parameters to a server, but I need to set up the proxy. can you help me to to sort it "setting the proxy" part of my code ?

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();
like image 284
Srpr Avatar asked Feb 10 '11 10:02

Srpr


2 Answers

Yes I sorted out my own problem,this line

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

should be

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

Complete Example of a Apache HttpClient 4.1, setting proxy can be found below

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();
like image 76
Srpr Avatar answered Nov 18 '22 22:11

Srpr


Non deprecated way of doing it (also in 4.5.5 version) is:

HttpHost proxy = new HttpHost("proxy.com", 80, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
                    .setRoutePlanner(routePlanner)
                    .build();
like image 59
Mazhar Avatar answered Nov 18 '22 22:11

Mazhar