将HttpCookie添加到CookieStore

时间:2017-08-14 14:55:59

标签: java

我需要添加一些cookie来在网站上进行授权。 Cookie已成功添加,但在提出请求时会丢失:

import java.io.*;
import java.net.*;

public class Main {
    static public void main(String[] args) throws Exception {
        CookieManager cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
        CookieStore cookieJar = cookieManager.getCookieStore();
        CookieHandler.setDefault(cookieManager);

        HttpCookie cookie = new HttpCookie("name123", "value123");
        cookieJar.add(new URI("http://httpbin.org"), cookie);

        HttpURLConnection connection = (HttpURLConnection) new URL("http://httpbin.org/cookies").openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        BufferedReader in;
        StringBuilder response = new StringBuilder();
        String inputLine;
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString());
    }
}

但我只得到一张空白的地图回复

{  "cookies": {}}

请告诉我应该怎么做才能解决它。

1 个答案:

答案 0 :(得分:0)

cookie.setPath( "/" );
cookie.setVersion( 0 );

执行技巧¯\_(ツ)_/¯