【问题标题】:My cookie doesn't seem to be getting added to HttpsUrlConnection in Android我的 cookie 似乎没有被添加到 Android 中的 HttpsUrlConnection
【发布时间】: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


    【解决方案1】:

    看起来不错。

    你得到一个空值的原因是你在连接之前不能查询标题。

    来自 URLConnection javadoc:

    以下方法用于访问标头字段和 与远程对象建立连接后的内容:

    • 获取内容
    • getHeaderField
    • 获取输入流
    • getOutputStream

    您确定这是您的服务器出错的地方吗?

    【讨论】:

    • HttpUrlConnection 方法 getErrorStream 对于调试此类错误很有用。
    • 我不能确定是不是问题,因为我不是服务器管理员。 errorStream 没有帮助The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
    • 我认为你的 setupConnection 方法设置了 connection.setDoOutput(true)?
    • 您正在设置服务器正在侦听的正确“Content-Type”标头?例如,connection.setRequestProperty("Content_Type", "application/x-www-form-urlencoded");
    猜你喜欢
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2017-05-15
    • 2015-05-13
    相关资源
    最近更新 更多