I'm trying to use OkHttp library to send post request to API with some url parameters. Following this blog post I have this code so far:
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();
}
The exception is:
javax.net.ssl.SSLPeerUnverifiedException: Hostname {domain} not verified:
Apparently you try to connect to a SSL website (https), therefore you need to add a
SSLSocketFactory
, below little code snippet.For more details see this page or this, it should help you.
If you want to "trust all certificates", see this example but it`s not recommanded and should only be used for testing purposes!
Check SSLSession hostname and your connection host name...
UPDATE
Code for
com.squareup.okhttp3:okhttp:3.0.1
Because your project uses OkHttp v3.0.0-RC1, so to fix that Exception, your code should be as the following sample:
However, instead of
return true;
above, I suggest that you read Google's documentation about Common Problems with Hostname Verification for more information.One more useful link is OkHttp's HTTPS wiki.
Hope it helps!
P/S: please note that I use async way of OkHttp (at client.newCall(request).enqueue(new Callback()...), you can also use sync way as your code.