Java Request类携带cookie
时间: 2023-05-24 08:03:51 浏览: 327
可以使用Java的HttpURLConnection或者HttpClient类来发送带有cookie的请求。可以通过以下步骤来实现:
1. 创建一个URL对象或者URI对象,表示要发送请求的URL地址。
2. 创建一个HttpURLConnection或者HttpClient对象来发送请求。
3. 设置请求头,包括cookie信息。
4. 发送请求并等待响应,可以通过getInputStream来获取服务器响应。
下面是一个使用HttpURLConnection发送带有cookie的请求的示例代码:
```
import java.net.*;
import java.io.*;
public class HttpRequest {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.example.com/login");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Cookie", "sessionId=xxxx; otherCookie=yyyy");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes("username=user&password=pass");
wr.flush();
wr.close();
// Get response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print response
System.out.println(response.toString());
}
}
```
在上述代码中,我们通过设置请求头中的Cookie属性来携带cookie信息。具体而言,我们在请求头中设置了 sessionId=xxxx 和 otherCookie=yyyy 两个cookie信息。
阅读全文
相关推荐


















