【问题标题】:Get cookies from redirect URL从重定向 URL 获取 cookie
【发布时间】:2015-08-05 08:36:03
【问题描述】:

我有一个 url,它进行 2 次内部重定向,然后最终返回 ok 响应。
第一个 URL:http://www.someurl.com/
重定向 URL 1:http://www.someurl_1.com/,响应为 302
重定向 URL 2: strong>:http://www.someurl_2.com/,响应为 302
最终网址:http://www.finalurl.com/,响应为 200
在内部重定向 URL 1 发送一些 cookie 到 重定向 URL 2。 我要做的是获取为 Redirect URL 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. 我已禁用重定向,此响应为我提供了此过程的第一个 url。
  2. 我已使用 Jsoup 禁用重定向,其输出与上述相同。

虽然在 ruby​​ 中可以获取这种重定向的 cookie,但我已经做到了。
但我必须在java中做到这一点。 httpclient 4.5

【问题讨论】:

    标签: java httpclient


    【解决方案1】:

    这对我有用

      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】:

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

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

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

      【讨论】:

      • 感谢提示,DefaultRedirectStrategy 对我有用。
      【解决方案3】:

      我遇到了同样的问题,我有多个重定向,但我需要将每个响应中的 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);
      

      【讨论】:

        猜你喜欢
        • 2013-02-24
        • 1970-01-01
        • 2015-07-09
        • 1970-01-01
        • 2016-03-05
        • 2018-03-07
        • 2021-03-28
        • 2013-06-06
        • 2019-08-29
        相关资源
        最近更新 更多