我正在编写一个 post 方法,需要将 session cookie 附加到请求中。我使用 HttpsUrlConnection
类打开安全 SSL 连接。这很好用。我通过调用 connection.setRequestProperty("Cookie", TheCookieData)
将 cookie 添加到连接。
不幸的是,我的服务器返回了 500,我怀疑这与没有附加到 post 请求的 cookie 或正确的 cookie 有关。之后,我使用 setRequestProperty
将 cookie 添加到连接中,通过记录 Log.i(TAG, "Post cookie header = "+ connection.getHeaderField("Cookie")); 来检查连接现在是否具有 cookie;
但这会返回 null
。
问题 --> 我是否正确添加了 cookie,如果是,为什么 getHeaderField("Cookie")
返回 null
?
发布方法
public static boolean post(Object message, Context context) {
try {
HttpsURLConnection connection = (HttpsURLConnection) setupConnection(HttpMethod.POST);
connection.setSSLSocketFactory(getSslContext(context).getSocketFactory());
if(TheCookieManager.getCookieStore().getCookies().size() > 0) {
Log.i(TAG, "post found cookie " + TextUtils.join(";", TheCookieManager.getCookieStore().getCookies()));
connection.setRequestProperty("Cookie", TextUtils.join(";", TheCookieManager.getCookieStore().getCookies()));
}
JSONObject data = new JSONObject();
data.put("msg", message);
Log.i(TAG, "post data=" + data.toString());
OutputStream os = connection.getOutputStream();
os.write(data.toString().getBytes(UTF8));
os.flush();
Log.i(TAG, "Post cookie header = " + connection.getHeaderField("Cookie"));
int code = connection.getResponseCode();
connection.disconnect();
Log.i(TAG, "post data fed to server!, data= " + data.toString());
Log.i(TAG, "server responded with " + String.valueOf(code));
return code != 200;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
最佳答案
看起来不错。
您得到 null 的原因是因为在连接之前无法查询 header 。
来自 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
您确定这是您的服务器出错的地方吗?
关于java - 我的 cookie 似乎没有添加到 Android 中的 HttpsUrlConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987410/