我有一个应用程序,我使用retrofit2连接到rest api。每次我尝试使用它时,我都会得到一个错误:“连接失败”。我不知道问题出在哪里。我希望能够连接到rest api并使用我的GET请求。
public static final String APP_BASE_URL="http://URL.com/";
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(APP_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
MyApiendpoint apiService=retrofit.create(MyApiendpoint.class);
Call<Bmwsales> call=apiService.getVehicle(barCode);
call.enqueue( new Callback<Bmwsales>() {
@Override
public void onResponse(Call<Bmwsales> call, Response<Bmwsales> response) {
System.out.println("SUCCESSFULL!!!");
}
@Override
public void onFailure(Call<Bmwsales> call, Throwable t) {
System.out.println("FAILURE!!!"+t.getMessage());
}
});
public interface MyApiendpoint {
@GET("bmwsales/vin/{vin}")
Call<Bmwsales> getVehicle(
@Path("vin") String vin
);
}
我不知道哪里出了问题。我已经看了很多例子,但仍然不能理解。
发布于 2019-05-09 23:05:03
你的代码没有问题。
但我建议你检查并尝试一些东西
首先,请确保您使用的是最新版本的
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
第二,尝试添加一个截取程序到Retrofit,然后检查日志以查看发送到服务器的实际请求,以及您是否可以毫无问题地到达该
下面是一个使用Okhttp的示例
// Create a new object from HttpLoggingInterceptor
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// Add Interceptor to HttpClient
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
// Init retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APP_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client) // Set HttpClient to be used by Retrofit
.build();
不要忘记将Okhttp日志拦截器添加到您的依赖项中
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
第三,也许你的连接太慢了,你只需要增加超时时间就行了!
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.addInterceptor(interceptor).build();
发布于 2019-05-09 23:15:25
http://
和“连接失败”可能意味着,您必须添加允许与主机进行明文通信的network_security_config.xml
,或者为该应用程序接口安装有效的SSL证书。NetworkSecurityPolicy.isCleartextTrafficPermitted()
告知当前状态。这是我的answer和documentation的相似之处。一个人可能不会截获任何调用,因为它可能从未发生过;还要确保URL在浏览器中工作。如果vin
代表一个车辆识别号,我会称之为Call<Vehicle>
。
发布于 2019-05-09 23:42:35
您是否在清单中声明了互联网权限?
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<application ...
</manifest>```
EDIT :
Can check your base URL again please ? you can use fake API endpoint to be sure that the issue is not with your Retrofit configuration, yu can use this endpoint : [JSONPlaceholder][1]
[1]: https://jsonplaceholder.typicode.com/posts
https://stackoverflow.com/questions/56067920
复制相似问题