【发布时间】:2016-03-03 10:16:39
【问题描述】:
我正在编写一个需要将会话 cookie 附加到请求的 post 方法。我用HttpsUrlConnection 类打开了一个安全的SSL 连接。这工作正常。我通过调用connection.setRequestProperty("Cookie", TheCookieData) 将cookie 添加到连接中。
不幸的是,我的服务器返回了 500,我怀疑这与没有附加到发布请求的 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;
}
}
【问题讨论】:
标签: java android cookies http-headers