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

时间:2018-05-28 15:30:55

标签: java http cookies

我想从网站上读取两个数字(随机生成),然后用它们来计算结果,然后使用POST请求提交结果。为此,我还需要提交该会话的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);

现在我想发送包含该会话的answercookies的POST请求。这是部分实现的POST请求,仅包含一个参数(answer):

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 个答案:

答案 0 :(得分:2)

使用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创建BasicCookieStore。创建一个包含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);

答案 1 :(得分:0)

发送您的第一个请求如下: -

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);
相关问题