代码之家  ›  专栏  ›  技术社区  ›  Giorgos Myrianthous

检索cookie并在随后的post请求中发送它

  •  1
  • Giorgos Myrianthous  · 技术社区  · 6 年前

    我想从一个网站上读取两个数字(随机生成),然后用这个数字计算结果,然后用一个帖子请求提交结果。为此,我还需要提交该会话的cookie,以便系统知道在该特定会话中生成的随机数。

    为了读出我使用的数字 Jsoup :

    Document document = Jsoup.parse(Jsoup.connect("http://website.com/getNumbers").get().select("strong").text());
    String[] numbers = document.text().split(" ");
    String answer = methodThatComputesTheDesiredOutput(numbers);
    

    现在我要发送一个包含 answer cookies 那次会议。这是一个部分实现的post请求,只包含一个参数( 回答 ):

    HttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://website.com/submitAnswer");
    List<NameValuePair> params = new ArrayList<NameValuePair>(1);
    params.add(new BasicNameValuePair("answer", answer);
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    

    如何在读取文档时获取cookie,然后将其用作post请求的参数?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Ranjith    6 年前

    使用jsoup按以下方式提取cookie:

        Response response = Jsoup.connect("http://website.com/getNumbers").execute();
        Map<String, String> cookies = response.cookies();
        Document document = Jsoup.parse(response.body());
    

    使用使用JSoup提取的cookie创建basicCokieStore。创建一个包含cookie存储的httpcontext,并在执行下一个请求时传递它。

        BasicCookieStore cookieStore = new BasicCookieStore();
        for (Entry<String, String> cookieEntry : cookies.entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
            cookie.setDomain(".example.com");
            cookie.setPath("/");
            cookieStore.addCookie(cookie);
        }
    
    
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    
        HttpPost httpPost = new HttpPost("http://website.com/submitAnswer");
        List<NameValuePair> params = new ArrayList<NameValuePair>(1);
        params.add(new BasicNameValuePair("answer", answer);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    
        httpClient.execute(httpPost, localContext);
    
        2
  •  0
  •   codewizard    6 年前

    发送您的第一个请求,如下所示:

    Response res = Jsoup.connect("login Site URL")
            .method(Method.GET)
            .execute();
    

    现在,获取cookie并用cookie发送新的请求,如下所示:

     CookieStore cookieStore = new BasicCookieStore();
         for (String key : cookies.keySet()) {
            Cookie cookie = new Cookie(key, cookies.get(key));
            cookieStore.addCookie((org.apache.http.cookie.Cookie) cookie);
        }
           HttpClientContext context = HttpClientContext.create();
            context.setCookieStore(cookieStore);
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("http://website.com/submitAnswer");
            httpClient.execute(httpPost,context);