Skip to content

Instantly share code, notes, and snippets.

@eltabo
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eltabo/8931347 to your computer and use it in GitHub Desktop.
Save eltabo/8931347 to your computer and use it in GitHub Desktop.
RestTemplateTest + Timeouts
package snippet;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public class RestTemplateTest {
// For testing
public static void main(String... args) {
class NetworkInterceptor implements ClientHttpRequestInterceptor{
@Override
public ClientHttpResponse intercept(HttpRequest arg0, byte[] arg1, ClientHttpRequestExecution arg2) throws IOException {
return arg2.execute(arg0, arg1); //Nothing to do
}
}
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add( new NetworkInterceptor() );
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("172.15.2.27", 3128));
SimpleClientHttpRequestFactory s = new SimpleClientHttpRequestFactory();
s.setProxy(proxy);
s.setReadTimeout(5000);
s.setConnectTimeout(1000);
RestTemplate tpl = new RestTemplate(s); //Create the RestTemplate using our SimpleClientHttpRequestFactory
// RestTemplate tpl = new RestTemplate();
// SimpleClientHttpRequestFactory s = (SimpleClientHttpRequestFactory)tpl.getRequestFactory();
// s.setProxy(proxy);
// s.setReadTimeout(5000);
// s.setConnectTimeout(1000);
tpl.setInterceptors( interceptors ); //Set the interceptors
ClientHttpRequestFactory c = tpl.getRequestFactory(); //Get a InterceptingClientHttpRequestFactory wrapping our SimpleClientHttpRequestFactory
s.setReadTimeout(1000); //Modify timeouts
s.setConnectTimeout(1000);
try {
ClientHttpRequest r = c.createRequest(new URI("http://www.google.es"), HttpMethod.GET);
ClientHttpResponse rp = r.execute();
System.out.println(rp.getStatusCode());
} catch (Exception e) {
e.printStackTrace(); //Sure you get here a java.net.SocketTimeoutException: Read timed out
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment