繁体   English   中英

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

[英]How to create a cookie and use it in HttpURLConnection?

我有以下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)

你会使用这样的东西:

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 Client http://hc.apache.org/httpcomponents-client-ga/

在我看来,您可以创建一个HttpUrlConnection对象,分配一个Cookie List ,如下所示:

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);
}

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

要获得更高的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()));  

尝试这个:

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

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

    conn.connect();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM