如何创建cookie并在HttpURLConnection中使用它?

时间:2019-05-09 06:26:50

标签: java cookies httpurlconnection siteminder

我有以下python代码可创建cookie,并将其添加到会话中。使用HttpURLConnection的等效Java代码是什么?我基本上想使用生成的Cookie发出HTTP POST请求。

    session = requests.session()
    session.auth = (username, password)
    try:
        token = session.get(SITEMINDER_URL % server, verify=False)
        session.cookies.update(dict(SMSESSION=json.loads(token.content)['SMSESSION']))
    except Exception as ex:
        raise Exception("Failed in authenticating with siteminder", ex)
    response = session.post(api_url, headers=headers, verify=False, json=data)

4 个答案:

答案 0 :(得分:0)

您将使用以下内容:

HttpURLConnection httpconn = < some source to get a HttpURLConnection >;
String cookieName = "SMSESSION"; // note this is the default but SM can use other prefixes
String cookieValue = < your token content >;
httpurl.setRequestProperty("Cookie", cookieName + "=" + cookieValue);

另外,来自javadocs:注意:HTTP要求所有请求属性都可以合法地具有多个具有相同键的实例,以使用逗号分隔的列表语法,从而可以将多个属性附加到单个属性中

这使我指出直接使用HttpUrlConnection确实很笨拙。我建议您看一下HTTP客户端库,例如Apache HTTP客户端http://hc.apache.org/httpcomponents-client-ga/

答案 1 :(得分:0)

我认为,您可以创建一个HttpUrlConnection对象,分配一个List Cookies,如下所示:

List<String> cookies = new ArrayList<>();
//Or using a map With entries: Key and value for each cookie
cookies.add("User-Agent=MyUserAgent"); //etc...
URL site = new URL("https://myurl.com");
HttpsURLConnection conn = (HttpsURLConnection) site.openConnection();
for (String string: cookies) {
        conn.setRequestProperty("Cookie", string);
}

但这是最简单但不是最好的方法。

答案 2 :(得分:0)

要获得Cookie的更高抽象,请使用CookieManager和CookieStore类。这是一个示例:

HttpURLConnection connection
CookieManager cookieManager = new CookieManager();
HttpCookie cookie = new HttpCookie("cookieName","cookieValue");

cookieManager.getCookieStore().add(null,cookie);

connection.setRequestProperty("Cookie", String.join( ";", cookieManager.getCookieStore().getCookies()));  

答案 3 :(得分:0)

尝试一下:

    URL url = new URL("http://www.example.com");
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();

    conn.setRequestProperty("Cookie", "name1=value1; name2=value2");

    conn.connect();