Search code examples
javaandroidxamppretrofit

retrofit onFailure() keeps triggering on connecting to localhost


I want to connect to my localhost server for testing my app. For this reason, I am using the retrofit library. This is my interface class, which defines the url to connect to:

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface PostInterface {

    String JSONURL = "http://80.0.0.13/";
    @FormUrlEncoded
    @POST("login_screen/backend.php")
    Call<String>  getUserLogin(
        @Field("input") String input,
        @Field("username") String uname,
        @Field("password") String password
    );
}

I am calling this interface in my java code:

    Call<String> call = null;
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(PostInterface.JSONURL)
            .addConverterFactory(ScalarsConverterFactory.create())
            .build();

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

    call = api.getUserLogin("sign in", "abc", "abc@xyz");

     if (call != null) {
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.body() != null) {
                    Log.d("success",response.body());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), t.toString(), Snackbar.LENGTH_SHORT);
                snackbar.show();
            }
        });
     }

Strangely, the onFailure() method keeps triggering everytime with the following throwable:

javaSocketTimeoutException: Failed to connect to /80.0.0.13 (port 80)....

But when I try the url in my android browser or pc browser, it works fine.

Things I have checked:

  1. The project is stored inside C:\xampp\htdocs, having the exact same hierarchy as in my live server location.
  2. Both Apache and SQL ports are open in my xampp control panel.
  3. My localhost port number is default 80
  4. When I run the app in my emulator using this ip http://10.0.2.2:80/, then it works fine

Why is the app failing to connect to my local server?

EDIT: I can access my site from my phone browser using my pc ip address, but when I want to access it from the app, then the onFailure() triggers


Solution

  • After much struggling, I finally found the solution from a post in github:

    1. Turn on USB Tethering & USB Debugging Mode in your mobile.
    2. Connect your mobile to your laptop/desktop through USB.
    3. Now just change the ip address (run "ipconfig" in cmd)