How to make all network traffic go via a proxy?

2019-05-27 00:40发布

问题:

I have an app that makes http requests to a remote server. I do this with the following code:

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("myURL");

    try {

        ArrayList<BasicNameValuePair> postVariables = new ArrayList<BasicNameValuePair>(2);
        postVariables.add(new BasicNameValuePair("key","value"));

        httpPost.setEntity(new UrlEncodedFormEntity(postVariables));
        HttpResponse response = httpClient.execute(httpPost);
        String responseString = EntityUtils.toString(response.getEntity());

        if (responseString.contains("\"success\":true")){
            //this means the request succeeded
        } else {
            //failed
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

This goes really well, but one of our customers has set up an APN that requires requests to go via a certain proxy server. If I add the following to the request this works, the request gets rerouted via the proxy to the server:

    HttpHost httpHost = new HttpHost("proxyURL",8080);
    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpHost);

So far so good, however, I use a library that makes some http requests as well. The library's code is not accesible for me, so I can't add those two lines to the code. I contacted the creators of that library, and they told me it should be possible to set up the android environment so that all requests will automatically go through the proxy. Is there something like that? I didn't find anything on google.
I'm basically looking for a way to set the above two lines as a standard for all http requests. Please note that the APN does not set the proxy as a default for the entire phone, so apps will have to do this manually (and yes that means the majority of the apps don't work on that customer's phone).

回答1:


It's been a year or two since I've needed to use it, but if I remember correctly, you can use the System.setProperty(String, String) in order to set an environment-wide setting for your application to route all HTTP traffic through a proxy. The properties that you should need to set are "http.proxyHost" and "http.proxyPort" and then use your HttpClient normally without specifying a proxy because the VM will handle routing requests.
Docs for more information about what I'm talking about can be found here: ProxySelector (just so you know what keys to use) and here for documentation about the actual System.setProperty(String, String) function
If that doesn't work for you, let me know and I'll try to dig out my old code that set a system-level proxy. BTW, it's really only "system-level" since each app runs in it's own Dalvik so you won't impact other app's network communications.