gpt4 book ai didi

android - SSLPeerUnverifiedException OkHttp?

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:53 25 4
gpt4 key购买 nike

我正在尝试使用 OkHttp 库向带有一些 url 参数的 API 发送 post 请求。正在关注this blog post到目前为止我有这段代码:

    public String okHttpRequest() throws IOException{

OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {

return true;
}
});
HttpUrl.Builder urlBuilder = HttpUrl.parse("myurl").newBuilder();
urlBuilder.addQueryParameter("username","username");
urlBuilder.addQueryParameter("password","7777");
String url = urlBuilder.build().toString();

Request request = new Request.Builder()
.url(url)
.build();

//HERE EXCEPTION IS THROWN
Response response = client.newCall(request).execute();
return response.body().string();
}

异常(exception)情况是:

javax.net.ssl.SSLPeerUnverifiedException:主机名 {domain} 未验证:

最佳答案

更新

com.squareup.okhttp3:okhttp:3.0.1的代码

mTextView = (TextView) findViewById(R.id.textView);
mHandler = new Handler(Looper.getMainLooper());

final Request request = new Request.Builder()
.url("https://...")
.post(formBody)
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
Log.e(LOG_TAG, e.toString());
mHandler.post(new Runnable() {
@Override
public void run() {
String message = request.toString() + "\r\n" + e.toString();
mTextView.setText(message);
}
});
}

@Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
final String message = jsonObject.toString(5);
Log.i(LOG_TAG, message);
mHandler.post(new Runnable() {
@Override
public void run() {
mTextView.setText(message);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
});

因为您的项目使用OkHttp v3.0.0-RC1,所以要修复该异常,您的代码应如下例所示:

        OkHttpClient client = new OkHttpClient.Builder()
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.build();

Request request = new Request.Builder()
.url("https://...")
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
// do something...
}

@Override
public void onResponse(Response response) throws IOException {
// do something...
}
});

但是,我建议您阅读 Google 关于 Common Problems with Hostname Verification 的文档,而不是上面的 return true;获取更多信息。

一个更有用的链接是 OkHttp's HTTPS wiki .

希望对您有所帮助!

P/S: 请注意,我使用 OkHttp 的异步方式(在 client.newCall(request).enqueue(new Callback()...),您也可以使用同步方式作为您的代码。

关于android - SSLPeerUnverifiedException OkHttp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34671926/

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