Roro
Roro

Reputation: 457

How to fix "failed to connect" error when using retrofit2?

I have an app where I am using retrofit2 to connect to a rest api. Every time I try and use it I get the error: "failed to connect". I do not know what the problem is. I want to be able to connect to the rest api and use my GET request.

public static final String APP_BASE_URL="http://URL.com/";

Retrofit retrofit=new Retrofit.Builder()
    .baseUrl(APP_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

MyApiendpoint apiService=retrofit.create(MyApiendpoint.class);
Call<Bmwsales> call=apiService.getVehicle(barCode);

call.enqueue( new Callback<Bmwsales>() {

    @Override
    public void onResponse(Call<Bmwsales> call, Response<Bmwsales> response) {
        System.out.println("SUCCESSFULL!!!");
    }

    @Override
    public void onFailure(Call<Bmwsales> call, Throwable t) {
        System.out.println("FAILURE!!!"+t.getMessage());
    }
});

public interface MyApiendpoint {

    @GET("bmwsales/vin/{vin}")
    Call<Bmwsales> getVehicle(
        @Path("vin") String vin
    );
}

I'm not sure what is wrong. I've looked at numerous examples and still can't figure it out.

Upvotes: 3

Views: 10001

Answers (3)

ikerfah
ikerfah

Reputation: 2862

Did you declare Internet permission inside your manifest ?

<manifest xlmns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET" />
 <application ...
</manifest>```

EDIT : 
Can check your base URL again please ? you can use fake API endpoint to be sure that the issue is not with your Retrofit configuration, yu can use this endpoint : [JSONPlaceholder][1]


  [1]: https://jsonplaceholder.typicode.com/posts

Upvotes: 0

Martin Zeitler
Martin Zeitler

Reputation: 76679

http:// and "failed to connect" could mean, you have to add a network_security_config.xml which permits clear-text communication with the host or install a valid SSL certificate for the API. NetworkSecurityPolicy.isCleartextTrafficPermitted() tells the current status. here's a similar answer of mine and the documentation. one probably won't intercept any call, because it may have never happened; also make sure the URL is working in a browser. If vin represents a vehicle identification number, I'd call it Call<Vehicle>.

Upvotes: 0

Omar Albelbaisy
Omar Albelbaisy

Reputation: 827

There is no issue with your code.

But I recommend you to check and try a few things

First, make sure you are using the latest version of Retrofit

implementation 'com.squareup.retrofit2:retrofit:2.5.0'

Second, try to add an interceptor to Retrofit and then check the log to see the actual request sent to the server and if you can reach that URL without any problem

Here is an example using Okhttp

  // Create a new object from HttpLoggingInterceptor
  HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
  interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

  // Add Interceptor to HttpClient
  OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

  // Init retrofit object
  Retrofit retrofit = new Retrofit.Builder()
           .baseUrl(APP_BASE_URL)
           .addConverterFactory(GsonConverterFactory.create())
           .client(client) // Set HttpClient to be used by Retrofit
           .build();

And don't forget to add Okhttp logging interceptor to your dependencies

 implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

Third, maybe your connection is slow and you just need to increase the timeout!

 OkHttpClient client = new OkHttpClient.Builder()
         .readTimeout(60, TimeUnit.SECONDS)
         .connectTimeout(60, TimeUnit.SECONDS)
         .addInterceptor(interceptor).build();

Upvotes: 1

Related Questions