【问题标题】:Retrofit 2.6.2 is not working on Vodafone mobile data but works fine on WiFiRetrofit 2.6.2 不适用于 Vodafone 移动数据,但在 WiFi 上运行良好
【发布时间】:2020-08-02 17:14:02
【问题描述】:

请帮帮我我的一些应用用户抱怨或反馈他们的应用无法在移动数据上运行(沃达丰 4G),但可以在 wifi 上运行。

我正在使用 Retrofit-2.6.2okhttp3 - 4.2.2。

Retrofit.Builder()
    .baseUrl(baseurl)
    .addConverterFactory(GsonConverterFactory.create())
    .client(getClient())
    .build()

fun getClient(): OkHttpClient {
    return OkHttpClient.Builder().addInterceptor(HeaderIntercepter())
        .readTimeout(2, TimeUnit.MINUTES)
        .writeTimeout(2, TimeUnit.MINUTES)
        .connectTimeout(2, TimeUnit.MINUTES)
        .build()
}

API 是在 Amazon 服务器 上使用 http 和 https 制作的。

我身边缺少什么,请给我解决方案?

提前致谢。

【问题讨论】:

    标签: android android-studio networking retrofit retrofit2.6


    【解决方案1】:

    这是一些 4G 网络问题,就像在沃达丰网络中一样。此网络中 TCP 连接 的连接时间,即 connectTimeout 始终处于连接状态,因此 API 在 之前无法连接2 分钟,因为提到了 2 分钟

    的超时

    所以,我通过将 TCP 连接时间(connectTimeout 减少到 1 秒)来解决这个问题,代码如下:

    OkHttpClient.Builder()
            .addInterceptor(HeaderIntercepter())
            .callTimeout(2, TimeUnit.MINUTES)
            .connectTimeout(1, TimeUnit.SECONDS)
            .readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES)
            .build()
    

    如果您的 api 或 url 不需要 通过改造在数据发送和接收之间建立 TCP 连接,那么您可以这样做,现在对我来说工作正常。

    【讨论】:

      【解决方案2】:

      network-security-config 添加到 res/xml 文件夹

      <?xml version="1.0" encoding="utf-8"?>
          <network-security-config>
            <base-config cleartextTrafficPermitted="true">
             <trust-anchors>
              <certificates src="system" />
             </trust-anchors>
            </base-config>
          </network-security-config>
      

      manifest文件application标签中添加一行

      android:networkSecurityConfig="@xml/network_security_config"
      

      并确保在manifest 文件中授予internet 权限

      <uses-permission android:name="android.permission.INTERNET" />
      

      manifest文件中也添加这个

       <uses-library
              android:name="org.apache.http.legacy"
              android:required="false"/>
      

      在您的应用构建 gradle 中添加 useLibrary 'org.apache.http.legacy'

      android {
      compileSdkVersion 28
      defaultConfig {
          applicationId "your_application_id"
          minSdkVersion 15
          targetSdkVersion 28
          versionCode 1
          versionName "1.0"
          testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
          useLibrary 'org.apache.http.legacy'
      }
      

      【讨论】:

      • @DeePanShu 尝试使用legacy 希望这对你有用
      • 第一次加载需要 2 到 3 分钟左右,然后完美运行
      猜你喜欢
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      相关资源
      最近更新 更多