How to prevent apache http client from following a redirect

后端 未结 10 1786
独厮守ぢ
独厮守ぢ 2020-11-28 06:08

I\'m connecting to a remote server with apache http client. the remote server sends a redirect, and i want to achieve that my client isn\'t following the redirect automatica

10条回答
  •  有刺的猬
    2020-11-28 06:31

    The magic, thanks to macbirdie , is:

    params.setParameter("http.protocol.handle-redirects",false);
    

    Imports are left out, here's a copy paste sample:

    HttpClient httpclient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    
    // HTTP parameters stores header etc.
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.handle-redirects",false);
    
    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();
    
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    
    // connect and receive 
    HttpGet httpget = new HttpGet("http://localhost/web/redirect");
    httpget.setParams(params);
    response = httpclient.execute(httpget, localContext);
    
    // obtain redirect target
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader != null) {
        redirectLocation = locationHeader.getValue();
      System.out.println("loaction: " + redirectLocation);
    } else {
      // The response is invalid and did not provide the new location for
      // the resource.  Report an error or possibly handle the response
      // like a 404 Not Found error.
    }
    

提交回复
热议问题