gpt4 book ai didi

android - 覆盖 okhttp 请求中的 HOST header

转载 作者:行者123 更新时间:2023-12-04 18:00:41 24 4
gpt4 key购买 nike

我正在使用 okhttp 从我的 Android APK 发送一些 http 请求。由于某些服务器端代理要求,我希望 url 端点类似于:“https://api.example.com”,但是在 http 请求中,我想将 HOST header 覆盖为“Host:proxy.example.com” .我尝试使用类似的东西:

    HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.example.com")
.build();

okhttprequest = new com.squareup.okhttp.Request.Builder()
.url(url)
.method("GET", requestBody)
.header("Host", "proxy.example.com")
.build();

response = mOkHttpClient.newCall(okhttprequest).execute();

但是,当我查看网络包中的 http 请求时,HOST header 仍然是“api.example.com”。只是想知道,我实际上可以覆盖 HOST header 的任何建议吗?非常感谢!

最佳答案

我遇到了类似的问题。这就是我应用于您的案例的方式:

import javax.net.ssl.HttpsURLConnection;
import okhttp3.Dns;
import okhttp3.OkHttpClient;

OkHttpClient mOkHttpClient= new OkHttpClient.Builder()
.dns(hostname -> {
if(hostname.equals("proxy.example.com"))
hostname = "api.example.com";
return Dns.SYSTEM.lookup(hostname);
})
.hostnameVerifier((hostname, session) -> {
if(hostname.equals("proxy.example.com"))
return true;
return HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session);
}).build();

然后像这样更新你的代码:

  HttpUrl url = new HttpUrl.Builder()
.scheme("https")
//.host("api.example.com") don't use this host
.host("proxy.example.com") // use the one in the host header
.build();

okhttprequest = new com.squareup.okhttp.Request.Builder()
.url(url)
.method("GET", requestBody)
//.header("Host", "proxy.example.com") don't need anymore
.build();

response = mOkHttpClient.newCall(okhttprequest).execute();

问题是什么以及这个解决方案是如何工作的:

您希望在您的主机 header 中使用“proxy.example.com”,但 okhttp 还会使用它在给定 URL 中找到的内容创建此 header ,在您的情况下为“api.example.com”。

我找不到阻止 okhttp 这样做的方法。存在另一种方式。

我们在 URL 中使用“proxy.example.com”,这样 okhttp 创建的主机头将是“host: proxy.example.com”,然后我们还添加了 DNS 查找的特殊情况。

在“proxy.example.com”的 DNS 解析过程中,我们将主机更改为“api.example.com”,以便您的请求将转到具有“api.example.com”指向的 IP 地址的服务器。

这会产生副作用。您的服务器返回的证书将包含名称“api.example.com”,并且由于 URL 中的主机是“proxy.example.com”,主机名验证将失败。

为了防止这种情况,我们添加了一个特殊情况来验证“proxy.example.com”,如果在验证期间主机名是“proxy.example.com”,我们将返回 true。

'

关于android - 覆盖 okhttp 请求中的 HOST header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35834904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com