Android HttpClient Doesn't Use System Proxy Se

2019-01-13 16:58发布

问题:

When I create a DefaultHttpClient object and try to hit a webpage, the request isn't routed through the proxy I specified in Settings.

Looking through the API docs, I don't see anywhere where I can specify a proxy though Android does have a Proxy class that allows me to read the system's proxy settings.

Is there a way I can use the proxy settings in an HttpClient?

回答1:

Try:

DefaultHttpClient httpclient = new DefaultHttpClient();

HttpHost proxy = new HttpHost("someproxy", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

(culled from here)



回答2:

Firstly, I would make sure that the request is adhering to the proxy settings properties you set in the Android Device's settings. You can determine this via code by looking at the System class in android.provider.Settings;

To identify if the user had system proxy settings, you can do the following:

    System.getProperty("http.proxyHost");
    System.getProperty("http.proxyPort");

    System.getProperty("https.proxyHost");
    System.getProperty("https.proxyPort");

If you have an instance of DefaultHTTPClient, then you can check whether it has the relevant proxy settings as well.

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY);

These are all ways to 'get' the proxy settings, and the 'set' methods are implemented in the same way, either through System.setProperty or httpclient.setParams.

Hope this helped!



回答3:

I'm developing the Android Proxy Library that try to abstract the access to proxy settings for every Android version. You can easily get the proxy settings currently selected by the user.



回答4:

Try :

System.setProperty("http.proxyHost", <your proxy host name>);
System.setProperty("http.proxyPort", <your proxy port>);

or

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpHost httpproxy = new HttpHost("<your proxy host>",<your proxy port>);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,  httpproxy);

or

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