代码之家  ›  专栏  ›  技术社区  ›  zaitsman

仅对一个请求禁用OkHttp3中的重定向

  •  0
  • zaitsman  · 技术社区  · 4 年前

    我有一个单身汉( object 在Kotlin)中,持有 OkHttpClient 根据stack上的搜索,这是一条路要走。

    现在我来看一个场景,对于我应用程序中的一个请求,我需要跳过重定向以获取 Location 头球。

    这似乎是通过

    val client = OkHttpClient.Builder()
                .followRedirects(false)
                .followSslRedirects(false)
                .build()
    

    这很好,但是现在我需要存储两个 OkHttpClient 而非重定向的一个甚至不能一直使用,因为它只属于我的应用程序的登录流。

    是否可能(例如,可能通过编写网络拦截器?)只为一个请求禁用重定向?

    1 回复  |  直到 4 年前
        1
  •  2
  •   samthecodingman    4 年前

    根据 docs ,您应该使用一个主实例,然后基于该基本实例构建定制。

    // renamed solely to make it clear what's going on below
    val commonClient = OkHttpClient.Builder()
                       .followRedirects(true) // you can skip these calls, they are true by default
                       .followSslRedirects(true)
                       .build()
    

    然后,在“do login”函数中,您将创建一个基本客户端的分支。在引擎盖下,所有东西都将继续使用 commonClient 但是,使用这个“新”客户端发出的任何请求都将使用您覆盖的设置。这只是有点奇怪,迂回的语法。

    // fork the base instance
    val noRedirectClient = commonClient.newBuilder()
                           .followRedirects(false) // override the previous/default settings used by commonClient
                           .followSslRedirects(false)
                           .build()
    
    // make your request(s)
    
    // don't shutdown noRedirectClient, because it would also shutdown the
    // underlying commonClient instance because they share resources