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

标签 java android cookies http-headers

    我正在编写一个 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/

相关文章:

java - 键盘中断布局和行为

java - 将 Java 项目部署到 JBoss 服务器

Android:立即停止播放声音文件

java - 使用 MapReduce View 查询 Couchbase Lite 问题

java - Facebook Android 应用程序链接打开 Facebook 页面而不是 Play 商店

authentication - ASP.Net Core 2.2 SignInManager 'No sign-in authentication handler is registered for the scheme ' Identity.Application'

javascript - 检查 cookie 值是否在数组中

java - 从 ANT 运行 junitreport 时出现 OutOfMemoryError

java - 将 JS 函数传递给小程序作为事件监听器

javascript - 如何使用 jquery cookie 插件确定 cookie 是否存在?