gpt4 book ai didi

Java HttpURLConnection - 带 Cookie 的 POST

转载 作者:搜寻专家 更新时间:2023-10-30 21:32:33 26 4
gpt4 key购买 nike

我正在尝试发送带有 cookie 的发布请求。这是代码:

try {

String query = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value", "UTF-8");
String cookies = "session_cookie=value";
URL url = new URL("https://myweb");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

conn.setRequestProperty("Cookie", cookies);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(query);
out.flush();
out.close();

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();

// Send the request to the server
//conn.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

问题是请求是在没有 cookie 的情况下发送的。如果我只做:conn.connect();并且不发送数据,cookie 发送正常。我无法确切地检查发生了什么,因为连接是通过 SSL 进行的。我只检查响应。

最佳答案

根据 URLConnection javadoc:

The following methods are used to access the header fields and the 
contents AFTER the connection is made to the remote object:

* getContent
* getHeaderField
* getInputStream
* getOutputStream

您是否已确认在上述测试用例中请求已到达服务器?我看到您在 getOutputStream() 之后调用了 connect() 并被注释掉了。如果您取消注释并在 调用 getOutputStream() 之前向上移动,会发生什么情况?

关于Java HttpURLConnection - 带 Cookie 的 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5531099/

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