从重定向网址获取Cookie

时间:2015-08-05 08:36:04

标签: java httpclient

我有一个url,它会产生2个内部重定向,然后最终返回ok响应。
第一个网址http://www.someurl.com/
重定向网址1:http://www.someurl_1.com/,回复302
重定向网址2:http://www.someurl_2.com/,回复302
最终网址http://www.finalurl.com/,回复200
内部重定向网址1 将一些Cookie发送到重定向网址2 。 我要做的就是为重定向网址2 获取Cookie设置。

这是我的java代码。

 HttpClient client = HttpClientBuilder.create().build();
      HttpGet get = new HttpGet(myurl);
      get.setHeader("User-Agent", "Mozilla");
      get.setHeader("Accept"," text/html,application/xhtml+xml,application/xml;");
      get.setHeader("Accept-Language", "en-US,en;q=0.8");
      get.setHeader("Accept-Encoding"," gzip, deflate");
      get.setHeader("Connection","keep-alive");
      get.setHeader("Cookie",JSESSIONID+");
//    get.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
      Header[] requestheaders   =   get.getAllHeaders();
         System.out.println("requestheaders >>> ");
         for(Header header: requestheaders){
             System.out.println(header.getName()+"-------------------- "+header.getValue());
         }
      HttpResponse response = client.execute(get);
      System.out.println("response 7 "+response);
      System.out.println("Headers are");
      Header[] headers = response.getAllHeaders();
      for (int i = 0; i < headers.length; i++) {
          System.out.println((headers[i].getName()+"___________________"+headers[i].getValue()));
      }

此代码给出了最终响应,而不是中间重定向响应。
所以任何人都可以建议我做什么更好的方法。

我检查过的其他事情是: -

  1. 我已禁用重定向,此响应为我提供了此过程的第一个网址。
  2. 我已经使用Jsoup来禁用重定向,它提供与上面相同的输出。
  3. 虽然在ruby中可以获取这样的重定向cookie,但我已经这样做了 但我必须在java中这样做。 httpclient 4.5

3 个答案:

答案 0 :(得分:3)

如果您想要更好地控制重定向行为,可以更改http客户端的RedirectStrategy

您可以创建自己的RedirectStrategy并使用它:

HttpClient instance = HttpClientBuilder.create()
                     .setRedirectStrategy(new LaxRedirectStrategy()).build();

答案 1 :(得分:3)

这对我有用

  HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new DefaultRedirectStrategy() {   

          public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)  {
              boolean isRedirect=false;
              try {
                isRedirect = super.isRedirected(request, response, context);
                Header[] requestheaders =   response.getAllHeaders();
                 System.out.println("getAuthToken  >>> ");
                 for(Header header: requestheaders){
                     System.out.println(header.getName()+"-------------------- "+header.getValue());
                    if(header.getName().equalsIgnoreCase("Set-Cookie") && header.getValue().startsWith("auth-token")){
                      System.out.println("Auth_Cookie "+header.getValue().split(";")[0]);
                      auth_token    =   header.getValue().split(";")[0];
                  }
                 }
              } catch (ProtocolException e) {
                e.printStackTrace();
              }
              if (!isRedirect) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 301 || responseCode == 302) {
                  return true;
                }
              }
              return false;
            }
          }).build();
      HttpGet get = new HttpGet(url);
      client.execute(get);

有关更多技术细节,请查看我的博客here

答案 2 :(得分:0)

我遇到了同样的问题,即我进行了多次重定向,但是我需要将每个响应中的Cookie传递给重定向。我可能可以做更多的工作来弄清楚每个重定向真正需要哪些cookie,但是我只是建立了所有cookie的映射,并且每个重定向都从合并的重定向中获取了完整的cookie集。这是我的代码...

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

...

    RestTemplate restTemplate = new RestTemplate();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    RedirectStrategy rs = new DefaultRedirectStrategy() {
        Map<String, Header> cookies = new HashMap<>();

        @Override
        public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                                          HttpContext context) throws ProtocolException {
            //
            // Get the cookies out of the response so we can inject them into the redirect.
            //
            for (Header header : response.getHeaders("Set-Cookie")) {
                this.cookies.put(header.getName(), header);
            }

            HttpUriRequest redirect = super.getRedirect(request, response, context);

            for (Header cookie : this.cookies.values()) {
                redirect.addHeader("Cookie", cookie.getValue());
            }
            return redirect;
        }
    };

    final HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(rs).build();
    factory.setHttpClient(httpClient);
    restTemplate.setRequestFactory(factory);

    ResponseEntity<String> response = restTemplate.getForEntity("<my_url>", String.class);
相关问题