Ale*_*ley 1 java android call retrofit
我正在尝试从后端服务获取信息,并且我正在使用 Retrofit 来获取响应。
这是我的改造单例类,我使用了一个随机 api 作为示例。我在启动服务时使用自己的。
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class BaseRetrofit {
private static Retrofit retrofitInstance = null;
private BaseRetrofit() {};
public static Retrofit getRetrofitInstance() {
if (retrofitInstance == null) {
retrofitInstance = new Retrofit.Builder()
.baseUrl("http://192.168.1.155:5000")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofitInstance;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的主课程中,我初始化改造并拨打电话。
EndPoints myEndPoints = BaseRetrofit.getRetrofitInstance().create(EndPoints.class);
Call<List<JobItem>> jobs = myEndPoints.getJobs();
jobs.enqueue(new Callback<List<JobItem>>() {
@Override
public void onResponse(Call<List<JobItem>> call, Response<List<JobItem>> response) {
Log.d("SUCCESS", "LOADED JSON " + response.body().get(0).getJobType());
}
@Override
public void onFailure(Call<List<JobItem>> call, Throwable t) {
Log.d("ERROR", "ERROR LOADING JSON");
}
});
Run Code Online (Sandbox Code Playgroud)
这是我的端点接口。
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface EndPoints {
@GET("/getjobs/hardware")
Call<List<JobItem>> getJobs();
}
Run Code Online (Sandbox Code Playgroud)
后端服务启动后需要的 URL 是 http://my_ip_address:5000/getjobs/hardware 例如http://192.168.1.155:5000/getjobs/hardware这就是 JSON
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class BaseRetrofit {
private static Retrofit retrofitInstance = null;
private BaseRetrofit() {};
public static Retrofit getRetrofitInstance() {
if (retrofitInstance == null) {
retrofitInstance = new Retrofit.Builder()
.baseUrl("http://192.168.1.155:5000")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofitInstance;
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么电话总是转到 onFailure
如果应用程序正在调用的服务在您的本地计算机(或本地主机或 127.0.0.1)上运行,那么如果您使用模拟器调用它,则需要使用 10.0.2.2 作为 IP 地址。所以你的 URL 看起来像http://10.0.2.2:5000
此外,由于协议是 http,您需要在清单中添加允许明文。为此,最好的方法是在 res 目录中创建一个 xml 目录并添加一个 network-security-config.xml 文件,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">10.0.2.2</domain>
</domain-config>
</network-security-config>
Run Code Online (Sandbox Code Playgroud)
然后,将其添加到您的清单中,如下所示:
<application
....
android:networkSecurityConfig="@xml/network_security_config">
.....
.....
</application>
Run Code Online (Sandbox Code Playgroud)
如果错误再次发生,请尝试打印出可抛出的异常以了解更多信息。
快乐编码!
归档时间: |
|
查看次数: |
65 次 |
最近记录: |