我的 cookie 似乎没有添加到 Android 中的 HttpsUrlConnection

My cookie doesn't seem to be getting added to HttpsUrlConnection in Android

我正在编写一个 post 方法,该方法需要将会话 cookie 附加到请求。我用 HttpsUrlConnection class 打开了一个安全的 SSL 连接。这很好用。我通过调用 connection.setRequestProperty("Cookie", TheCookieData) 向连接添加了一个 cookie。

不幸的是,我的服务器 returns 500,我怀疑这与没有 cookie 或正确的 cookie 有关,附加到 post 请求。之后,我将 cookie 添加到 setRequestProperty 的连接中,我通过记录 Log.i(TAG, "Post cookie header = " + connection.getHeaderField("Cookie")); 检查连接现在是否有 cookie 但是这个 returns null

问题 --> 我添加 cookie 是否正确,如果是,为什么 getHeaderField("Cookie") 返回 null

Post 方法

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 的原因是你无法查询 headers 直到你连接。

来自 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

您确定这是您的服务器错误所在吗?