如何使用Retrofit发布HTTPS请求? [英] How to post HTTPS request using Retrofit?
本文介绍了如何使用Retrofit发布HTTPS请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过这个构建一个restAdapter:
I build a restAdapter by this:
return new RestAdapter.Builder()
.setEndpoint("https://www.xyz.com/")
.build()
.create(SafeUserApi.class);
然后在SafeUserApi.class(这是一个接口)我有:
then in the SafeUserApi.class (which is an interface) I have:
public interface SafeUserApi {
@POST("/api/userlogin")
void getUserLogin(@Body UserserLogin userLogin, Callback<LoginResult> cb);
}
但它不起作用。我错过了什么?
But it does not work. Did I miss something?
我试过Postman并且它有效。但是在我的设备中却没有。
I tried with Postman and it works. But in my device it doesn't.
我导入了这四个库:
compile files('libs/okhttp-2.1.0.jar')
compile files('libs/okhttp-urlconnection-2.1.0.jar')
compile files('libs/okio-1.0.1.jar')
compile files('libs/retrofit-1.8.0.jar')
推荐答案
public static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
} };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts,
new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext
.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient = okHttpClient.newBuilder()
.sslSocketFactory(sslSocketFactory)
.hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
这应该有效:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(YOUR_HTTPS_URL)
.setClient(getUnsafeOkHttpClient())
.build();
这篇关于如何使用Retrofit发布HTTPS请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文