如何从 retrofit2 调用本地主机?
How to call localhost from retrofit2?
我正在尝试从我的 android 模拟器访问本地主机 (127.0.0.1) 上的 API。我在 API.
上有一个断点
- 邮递员呼叫 API 没有任何问题。
- Google Chrome 在模拟器上调用 API 没有问题。
- 如果我将 URL 更改为互联网上的某些内容,例如“https://jsonplaceholder.typicode.com”
,我在模拟器上的应用程序可以调用 APIs
- 我在 android 模拟器上的应用无法调用本地主机 (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。截屏:
我的设置可能有什么问题?你能帮忙吗
您可能遇到了证书错误,因为您正在请求 HTTPS,但您的 chrome 屏幕截图的警告符号表明可能存在 SSL 问题。
尝试:
- 正在将您的基础 URL 更改为
http://10.0.2.2:44351
。
- Permitting cleartext traffic for that IP.
如果这没有帮助,您应该使用您看到的 logcat 错误更新您的问题。
我正在尝试从我的 android 模拟器访问本地主机 (127.0.0.1) 上的 API。我在 API.
上有一个断点- 邮递员呼叫 API 没有任何问题。
- Google Chrome 在模拟器上调用 API 没有问题。
- 如果我将 URL 更改为互联网上的某些内容,例如“https://jsonplaceholder.typicode.com” ,我在模拟器上的应用程序可以调用 APIs
- 我在 android 模拟器上的应用无法调用本地主机 (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。截屏:
我的设置可能有什么问题?你能帮忙吗
您可能遇到了证书错误,因为您正在请求 HTTPS,但您的 chrome 屏幕截图的警告符号表明可能存在 SSL 问题。
尝试:
- 正在将您的基础 URL 更改为
http://10.0.2.2:44351
。 - Permitting cleartext traffic for that IP.
如果这没有帮助,您应该使用您看到的 logcat 错误更新您的问题。