【问题标题】:Retrofit2 Set-Cookie not present in responseRetrofit2 Set-Cookie 响应中不存在
【发布时间】:2017-07-22 09:12:47
【问题描述】:

我的服务端在客户端响应中发送 Set-Cookie,但在 Android 端我没有收到任何与标头中的 Set-Cookie 相关的信息。 我在 android 上的网络堆栈是 Retrofit 2。

这是我的请求代码,

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        String hostName = "https://www.mysupercoolhost.com";
        CertificatePinner certificatePinner = new CertificatePinner.Builder()
                .add(hostName, "sha256/p1")
                .add(hostName, "sha256/p2")
                .add(hostName, "sha256/p3")
                .build();
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(interceptor)
                .certificatePinner(certificatePinner)
                .build();
        RequestBody rb = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), "{\"user\":\"test\"}");

        Request request = new Request.Builder()
                .method("POST", rb)
                .addHeader("Content-Type", "application/json")
                .url(hostName)
                .addHeader("param1", "value1")
                .addHeader("param2", "value2")
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    client.newCall(request).execute();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();

同一段代码在 Simple Java 应用程序中有效,我可以看到在 Set-Cookie 键中转储的值,但在 Android 上失败。

请注意,我的 java 应用程序是仅具有 retrofit2 依赖项的 maven 项目。

在桌面上收到的 Cookie 类似于

INFO: Set-Cookie: test_443=9182912.910219021.0000; path=/
Mar 03, 2017 11:53:08 AM okhttp3.internal.Platform log
INFO: Set-Cookie: cutypie=wandarabigstring; Path=/
Mar 03, 2017 11:53:08 AM okhttp3.internal.Platform log

【问题讨论】:

    标签: android cookies httpurlconnection retrofit2 okhttp


    【解决方案1】:

    最后我让它工作了,我不得不使用 okhttpbuilder 手动设置 dns。 我的代码在桌面上运行的原因是因为

    cat /etc/hosts
    

    曾经

    127.0.0.1   localhost
    255.255.255.255 broadcasthost
    :1             localhost 
    x.x.x.x  mysupercoolhost.com
    

    我的安卓设备没有这个信息

    所以我不得不写

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.dns(new Dns() {
                @Override
                public List<InetAddress> lookup(String hostname) throws UnknownHostException {
                    return return Collections.unmodifiableList(Collections.singletonList(InetAddress.getByAddress("mysupercoolhost.com", domain_ip_in_bytes)));
                }
    
        });
    

    【讨论】:

      猜你喜欢
      • 2019-04-25
      • 2020-04-21
      • 1970-01-01
      • 2014-02-26
      • 2018-03-16
      • 2015-07-05
      • 2019-08-01
      • 1970-01-01
      相关资源
      最近更新 更多