【问题标题】:How to call localhost from retrofit2?如何从 retrofit2 调用 localhost?
【发布时间】:2021-04-05 14:31:42
【问题描述】:

我正在尝试从我的 android 模拟器访问 localhost(127.0.0.1) 上的 API。我在 API 上有一个断点。

  1. Postman 调用 API 没有问题。
  2. 模拟器上的 Google Chrome 调用 API 没有问题。
  3. 如果我将 URL 更改为 Internet 上的某些内容(例如“https://jsonplaceholder.typicode.com”),我在模拟器上的应用程序可以调用 API
  4. 我在 android 模拟器上的应用程序无法调用 localhost(127.0.0.1) 上的 API。它不会激活 API 操作上的断点。

改造代码:

public class TestApiContainer {

    public interface TestApi {

        @GET("EmptyTest/test")
        Call<String> test();
    }

    static TestApi testApi;

    public static TestApi api(){
        if (testApi == null)
            testApi = new Retrofit
                    .Builder()
                    .baseUrl("https://10.0.2.2:44351")
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                    .create(TestApi.class);
        return testApi;
    }
}

调用代码:

TestApiContainer.api().test().enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        
        if (!response.isSuccessful())
            return;
    }
});

邮递员截图:

它也适用于 Android 模拟器的 Google Chrome。截屏:

我的设置可能有什么问题?你能帮忙吗?

【问题讨论】:

  • 这个question 可能会有所帮助。 lmk
  • 没有帮助。如果是的话,我一开始就不会问这个问题。我已经在使用 10.0.2.2 而不是 localhost。

标签: android retrofit2


【解决方案1】:

您可能遇到证书错误,因为您请求的是 HTTPS,但您的 chrome 屏幕截图的警告符号表明可能存在 SSL 问题。

试试:

  1. 将您的基本 URL 更改为 http://10.0.2.2:44351
  2. Permitting cleartext traffic for that IP

如果这没有帮助,您应该使用您看到的 logcat 错误更新您的问题。

【讨论】:

    猜你喜欢
    • 2018-12-22
    • 2017-08-09
    • 1970-01-01
    • 2020-04-27
    • 2018-02-05
    • 2021-05-20
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    相关资源
    最近更新 更多