Monday, July 29, 2013

Connect with RestTemplate via Proxy Server

If you try to connect to Rest Url, and if you are using a Proxy Server and try to connect with RestTemplate Client you will have an error like this:

"407 Proxy Authentication required"

You will have to configure your RestTemplate by the following steps:

private final static String PROXY_HOST = "url";
private final static int PROXY_PORT=9999;
private final static String PROXY_USER = "user";
private final static String PROXY_PASSWORD = "pass";
...
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
DefaultHttpClient defaultHttpClient = (DefaultHttpClient)factory.getHttpClient();
defaultHttpClient.getCredentialsProvider().setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
new UsernamePasswordCredentials(PROXY_USER,
PROXY_PASSWORD));
factory.setHttpClient(defaultHttpClient);
restTemplate.setRequestFactory(factory);
Response respuesta = restTemplate.postForObject(DEV_RESTFUL, r,Response.class,vars);
...
After of that, you should be put httpclient jar in your classpath, download it from http://hc.apache.org/httpclient-3.x/

If you try to connect again with a UnitTest that will fix your problem.

Best Regards,

No comments:

Post a Comment