【问题标题】:How to fix "failed to connect" error when using retrofit2?使用retrofit2时如何解决“连接失败”错误?
【发布时间】:2019-05-10 23:33:04
【问题描述】:

我有一个应用程序,我在其中使用 retrofit2 连接到休息 api。每次我尝试使用它时,我都会收到错误消息:“连接失败”。我不知道问题是什么。我希望能够连接到其余 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
    );
}

我不确定出了什么问题。看了很多例子还是搞不懂。

【问题讨论】:

    标签: java android retrofit2


    【解决方案1】:

    您的代码没有问题。

    但我建议你检查并尝试一些事情

    首先,确保您使用的是最新版本的 Retrofit

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    

    其次,尝试向 Retrofit 添加拦截器,然后检查日志以查看发送到服务器的实际请求,以及是否可以毫无问题地访问该 URL

    这里是一个使用 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();
    

    【讨论】:

    • 我无法在拦截器上设置级别。它不承认“设定水平”。怎么了?
    • 好的,我可以设置级别了。我增加了超时,它仍然说连接失败。
    • 您确定可以从浏览器访问打印在 Logcat 中的请求 URL(启用日志记录后)吗?
    • 是的。在 okhttp 日志中,它显示 URL:9083/api/bmwsales/vin/mystring,然后我在浏览器中找到它,它的 URL:9083/api/bmwsales/vin/mystring 就出现了。
    • 您是否尝试连接到公共域或本地 IP 地址?而且,您是否在其他移动设备上尝试过该应用?
    【解决方案2】:

    http:// 和“连接失败”可能意味着您必须添加一个network_security_config.xml,它允许与主机进行明文通信或为 API 安装有效的 SSL 证书。 NetworkSecurityPolicy.isCleartextTrafficPermitted() 告诉当前状态。这是我的一个类似的answer 和documentation。一个人可能不会拦截任何电话,因为它可能从未发生过;还要确保 URL 在浏览器中工作。如果vin 代表车辆识别号,我会称之为Call&lt;Vehicle&gt;。

    【讨论】:

      【解决方案3】:

      您是否在清单中声明了 Internet 权限?

      <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
      

      【讨论】:

      • 当我更改基本网址时,它说无法解析主机:没有与主机名关联的地址。所以这是正确的,因为我故意拼错了主机名。
      • 您可以发布您的基本网址以便我可以帮助您吗?
      猜你喜欢
      • 1970-01-01
      • 2019-07-04
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多