gpt4 book ai didi

java - 在 Java 代码中接受 Cookies?

转载 作者:行者123 更新时间:2023-11-30 11:58:58 25 4
gpt4 key购买 nike

我正在处理一个 HTTP 套接字项目,我必须像这样从我的 Java 代码发送 2 个 HTTP GET 请求:

  • 请求 1:调用页面 X
  • 页面 X 正在设置 cookie。
  • 请求 2:调用页面 Y

如您所见,要访问页面 Y 的内容,必须存在 cookie...

请问如何接受来自 java 代码的 cookie?

这是一个示例发送请求:

      String sServer = "example.com";
InetAddress inaddr = null;

try {
inaddr = InetAddress.getByName(sServer);
}
catch (UnknownHostException ex) { //The host could not be resolved.
System.out.println(ex);
System.out.println("Error resolving hostname for '" + sServer + "'.\n");

}
Socket sock = null;
try {
sock = new Socket(inaddr, 80);
}
catch (IOException ex) {
System.out.println(ex);
System.out.println("Could not create the socket.\n");

}

try {
java.io.OutputStream os = sock.getOutputStream();
String sPacket = "GET /xxx/xxx/xxx.do HTTP/1.1\n" + "Host: example.com\n"
+ "Connection: keep-alive\n" + "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.1.249.1064 Safari/532.5\n"
+ "Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8\n\n";

os.write(sPacket.getBytes(), 0, sPacket.length());

//Let's get the answer.
System.out.print("The server (" + sServer + ") answered: '");
java.io.InputStream is = sock.getInputStream();
byte[] buf = new byte[1024];
is.read(buf, 0, buf.length);
for (int i = 0; i < buf.length; i++) {
if (buf[i] == 0) break;
else
System.out.print(new Character((char)buf[i]));
}
System. out.print("'\n");

}
catch (Exception ex) {
System.out.println(ex);

}

最佳答案

强烈推荐使用HttpClient或另一个专用于 HTTP 处理的库,而不是尝试自己实现/解释协议(protocol)。参见 here了解如何使用 HttpClient 处理 cookie。

关于java - 在 Java 代码中接受 Cookies?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2795791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com