【发布时间】:2021-04-05 14:31:42
【问题描述】:
我正在尝试从我的 android 模拟器访问 localhost(127.0.0.1) 上的 API。我在 API 上有一个断点。
- Postman 调用 API 没有问题。
- 模拟器上的 Google Chrome 调用 API 没有问题。
- 如果我将 URL 更改为 Internet 上的某些内容(例如“https://jsonplaceholder.typicode.com”),我在模拟器上的应用程序可以调用 API
- 我在 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。