首页 > 解决方案 > HTTPS Get请求在android retrofit2中不起作用

问题描述

我想使用 android retrofit2 向我的服务器发送 https 获取请求。

如果我使用 http 发送相同的请求,它工作正常。

每当我发送 https 请求时不起作用。

我的端点:

https://xxxx:xxx@xxx/rest/xxx

我的代码片段:

String base = uname + ":" + pwd;

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        Request.Builder requestBuilder = original.newBuilder()
            .header("Authorization", base);

        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
});

OkHttpClient client = httpClient.build();

Retrofit rulesRetrofit = new retrofit2.Retrofit.Builder()
    .baseUrl(HttpsRuels)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();
cloudRulesDataInterface = rulesRetrofit.create(APInterface.class);

Call < ResponseBody > rulesCall = cloudRulesDataInterface.getRulesFromCloud();
rulesCall.enqueue(new Callback < ResponseBody > () {
    @Override
    public void onResponse(Call < ResponseBody > call, Response < ResponseBody > response) {
        if (response.isSuccessful()) {
            try {
                Log.d(TAG, "response from success =" + response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                Log.d(TAG, "response from error =" + response.errorBody().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFailure(Call < ResponseBody > call, Throwable throwable) {

    }
});

我总是从服务器收到未经授权的响应。当我在邮递员中进行测试时,它工作正常。但在 android 中无法正常工作。

标签: androidretrofit2

解决方案


参考这个答案。您需要在改造代码逻辑中启用 SSL 证书使用。

HTTPS 改造


推荐阅读