怎么给http请求添加cookie

本文介绍如何在HTTP请求中设置单个及多个Cookie值。包括创建Cookie字符串,并通过URLConnection的setRequestProperty方法将其添加到请求头中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Setting a cookie value in a request:

1.
Values must be set prior to calling the connect method:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
2.
Create a cookie string:
String myCookie = "userId=igbrown";
3.
Add the cookie to a request:
Using the setRequestProperty(String name, String value); method, we will add a property named "Cookie", passing the cookie string created in the previous step as the property value.

urlConn.setRequestProperty("Cookie", myCookie);
4.
Send the cookie to the server:
To send the cookie, simply call connect() on the URLConnection for which we have added the cookie property:

urlConn.connect()


Setting a multiple cookie values in a request:


1.
Perform the same steps as the above item (Setting a a cookie value in a request), replacing the single valued cookie string with something like the following:
String myCookies = "userId=igbrown; sessionId=SID77689211949; isAuthenticated=true";
This string contains three cookies (userId, sessionId, and isAuthenticated). Separate cookie name/value pairs with "; " (semicolon and whitespace).

Note that you cannot set multiple request properties using the same name, so trying to call the setRequestProperty("Cookie" , someCookieValue) method will just overwrite any previously set value.
原文摘自:http://www.hccp.org/java-net-cookie-how-to.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值