Search code examples
androidspringproxyspring-android

Android Spring RestTemplate with Proxy


i need to read the proxy information from the phone and if the phone is under a proxy i need to set this proxy on my spring restTemplate object.I've tried the follow code without any luck, could anyone tell me what i'm doing wrong.

String proxyHost = android.net.Proxy.getHost(activity
            .getApplicationContext());

SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, 8080));
requestFactory.setProxy(proxy);
RestTemplate rest = new RestTemplate(requestFactory);

Thanks for any help


Solution

  • I've found the answer for my question .. will post here the code:

     if (proxyHost != null && proxyPort != null) {
            rest = new RestTemplate();
            HttpComponentsClientHttpRequestFactory factory =   ((HttpComponentsClientHttpRequestFactory) rest
                    .getRequestFactory());
            DefaultHttpClient defaultHttpClient = (DefaultHttpClient) factory
                    .getHttpClient();
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            defaultHttpClient.getParams().setParameter(
                    ConnRoutePNames.DEFAULT_PROXY, proxy);
    
        } else {
            rest = new RestTemplate();
            HttpComponentsClientHttpRequestFactory factory = ((HttpComponentsClientHttpRequestFactory) rest
                    .getRequestFactory());
            DefaultHttpClient defaultHttpClient = (DefaultHttpClient) factory
                    .getHttpClient();
    
        }