Announcement Announcement Module
Collapse
No announcement yet.
Disabling followredirect in resttemplate Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Disabling followredirect in resttemplate

    Hello Folks,

    We are calling a Rest WebService thru RestTemplate which returns a 302 response. We want to catch the 302 response and not follow the redirect/ The problem is that restTemplate automatically follows the redirect request and directly takes us to the next page. Is there a way we can disable the followredirect in resttemplate?

    This is how we call

    Code:
    RequestCallbackDecorator rc = new RequestCallbackDecorator(providerToken);
    		ResponseExtractorbackDecorator rx = new ResponseExtractorbackDecorator();
    
    HttpHeaders requestHeaders = new HttpHeaders();
    		requestHeaders.set("Authentication", providerToken);
    
    		
    		HttpEntity<?> requestEntity = new HttpEntity<String>(requestHeaders);
    		
    	
    		ClientHttpResponse response  = restTemplate.execute(url, HttpMethod.GET, rc, rx);



    In httpClient we have

    Code:
    GetMethod method = new GetMethod();
    	    method.setFollowRedirects( false );
    Do we have something like this in resttemplate?

    I am also catching the ClientHttpResponse thru ResponseExtractor

    Code:
    private class ResponseExtractorbackDecorator implements ResponseExtractor
    	{
    
    		@Override
    		public Object extractData(ClientHttpResponse response)
    				throws IOException {
    			log.debug("Status Code=>"+response.getStatusCode());
    			
    			return response;
    		}
    	
    	}
    but it looks like resttemplate implicity follows redirect since we directly get 200 in extractData and the response body shows html for the page that is being redirected?

    Any inputs are highly appreciated..
    thanks,
    Aseem

  • #2
    If you are using SimpleClientHttpRequest, which uses JDK's HttpUrlConnection,
    you can use HttpUrlConnection.setFollowRedirects(false) to disable follow redirects for all subsequently created HttpUrlConnections. I think this can also be done via a system property. But anyway, it won't work for RestTemplate, as the implementation of spring version 3.0.5 of SimpleClientHttpRequestFactory explicitly enables follow redirects (using HttpUrlConnection.setInstanceFollowRedirects(true) ), only for GET method, and explicitly disables it for other methods.
    You can extend SimpleClientHttpRequestFactory overriding prepareConnection method and configure RestTemplate with an instance of your custom factory. You can do that via constructor or via setter (requestFactory property).

    Comment

    Working...
    X