首页 > 解决方案 > 我无法在 android 应用程序中使用 RestApi

问题描述

这是我的 RestApi 获取调用结果 RestApi

在我的 android 应用程序中,我使用改造库来调用此 api 以显示我的 android 应用程序中的项目,这是 android 中的 api 调用

package com.aditmsolutions.www.foodie;
import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;

public interface Api {
    String BASE_URL = "https://10.0.2.2:51087/api/";
    @GET("items")
    Call<List<Item>> getItems();
}

当我运行我的应用程序时,它会显示此错误消息“握手失败” 错误 请帮助

这是logcat视图

她是getItems的代码

private void getItems() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Api.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()) //Here we are      using the GsonConverterFactory to directly convert json data to object
            .build();

    Api api = retrofit.create(Api.class);

    Call<List<Item>> call = api.getItems();

    call.enqueue(new Callback<List<Item>>() {
        @Override
        public void onResponse(Call<List<Item>> call, Response<List<Item>>   response) {
            List<Item> itemList = response.body();

            //Creating an String array for the ListView
            String[] items = new String[itemList.size()];

            //looping through all the heroes and inserting the names inside the string array
            for (int i = 0; i < itemList.size(); i++) {
                items[i] = itemList.get(i).getTitle();
            }


            //displaying the string array into listview
            listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, items));

        }

        @Override
        public void onFailure(Call<List<Item>> call, Throwable t) {
            Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

标签: androidapiretrofitretrofit2

解决方案


您在https certificate验证中的问题。如果您想接受所有受信任/不受信任的证书,请在您的项目中使用此客户端。你的问题将得到解决。

翻新建筑商:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Api.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()) //Here we are      using the GsonConverterFactory to directly convert json data to object
            .client(UnsafeOkHttpClient.getUnsafeOkHttpClient())
            .build();

不安全的客户端:

public class UnsafeOkHttpClient {  
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[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
}

推荐阅读