Using Retrofit getting error onFailure: com.google

2020-06-04 04:30发布

问题:

I am getting error while adding OkHttpClient object into retrofit.

Error is: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: closed

Here is My Code:

public static OkHttpClient getUnsafeOkHttpClient() {

    try {
        File mFolder = new File(Environment.getExternalStorageDirectory() + "/certificate");
        if (!mFolder.exists())
        {
            mFolder.mkdir();
        }

        String fileName = "certificate1a.cer";

        File file = new File(mFolder, fileName);

        FileInputStream fis = null;

        fis = new FileInputStream(file);

        CertificateFactory cf = CertificateFactory.getInstance("X.509");


        Certificate ca = cf.generateCertificate(fis);

        // Create a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TSL");
        sslContext.init(null, tmf.getTrustManagers(),null);
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.interceptors().add(new APIRequestInterceptor());
        okHttpClient.interceptors().add(new APIResponseInterceptor());

        okHttpClient.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession sslSession) {
                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
                Log.e("hey", "inside this");
                Log.e("HOST VERIFIER", hv.toString());
                Log.e("HOST NAME", hostname);
                return hv.verify("aviatesoftware.in", sslSession);
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        Log.e("error while getting ","unsafeOkHttpClient "+e.toString());
    }
    return null;
}

public static <S> S createService(Class<S> serviceClass) {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(API_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(getUnsafeOkHttpClient())
            .build();

    return retrofit.create(serviceClass);
}


GetInterface obj  = createService(GetTaxInterface.class);
            Call<Abc> call = obj.getAbc("555555555555");
            call.enqueue(new Callback<Abc>() {



                @Override
                public void onResponse(Response<Abc> response, Retrofit retrofit) {
                    Log.e("Asynchronous response", response.toString());

                    Abc temp = response.body();
                    Log.e("tax object", temp.toString());
                    Toast.makeText(getApplicationContext(),"Retrofit Asynchonus Simple try successful",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Throwable t) {
                    Log.e("on Failure", t.toString());
                    Toast.makeText(getApplicationContext(),"Retrofit Asynchonus Simple try failed",Toast.LENGTH_SHORT).show();
                }
            });

I have include below gradle files.

  • compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
  • compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
  • compile 'com.squareup.okhttp:okhttp:2.7.0'

With All above code i am getting error which is on Failure: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: closed

i have tried some combination like below.

if i simply used OkHttpClient okhttpclient = new OkHttpClient() instead of getUnsafeOkHttpClient()

And add this okhttpclient object to retrofit like .client(okhttpclient) instead of .client(getUnsafeOkHttpClient()) i do not get any error. it will execute onResponse()

I have to use getUnsafeOkHttpClient() for security purpose. can anyone tell me where i am doing wrong?

回答1:

Note that Retrofit 2 relies on OkHttp for its network operations Hence you will not need to add OkHttp dependency explicitly once you have added the retrofit2. I believe that could be causing the version conflict.

Edit: Use beta 3 for both retrofit and gson

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:retrofit-converters:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3