【问题标题】:java.net.SocketException: Connection reset on requesting http endpoint on Androidjava.net.SocketException:在 Android 上请求 http 端点时连接重置
【发布时间】:2022-11-26 13:17:00
【问题描述】:

出于学习目的,我需要请求 http 端点。

我已设置为允许 http 请求,但我一直在客户端收到 java.net.SocketException: Connection reset 异常,在服务器端收到 java.io.IOException: Connection reset by peer 异常。

当我使用 https 协议请求相同的服务器应用程序时 - 一切正常。使用邮递员请求时,http 端点也能正常工作

如何让 Android 允许 http 请求?

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

  <application android:networkSecurityConfig="@xml/network_security_config">
    ...
  </application>
</manifest>

network_security_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">192.168.1.2</domain>
  </domain-config>
</network-security-config>

改造设置:

fun provideRetrofit(context: Context): MyApi {
  val cache = Cache(context.cacheDir, CACHE_SIZE)
  val okHttpClient = OkHttpClient.Builder()
      .cache(cache)
      .build()
  val retrofit: Retrofit = Retrofit.Builder()
      .baseUrl(BUSSO_SERVER_BASE_URL)
      .addConverterFactory(
          GsonConverterFactory.create(
              GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create()
          )
      )
      .client(okHttpClient)
      .build()
  return retrofit.create(MyApi::class.java)
}

要求:

@GET("http://192.168.1.2:8080/api/v1/findBusStop/{lat}/{lng}")
  suspend fun findBusStopByLocation(
      @Path("lat") latitude: Double,
      @Path("lng") longitude: Double,
      @Query("radius") radius: Int
  ): List<BusStop>

【问题讨论】:

  • 192.168.1.2 不是域,所以我认为您的方法行不通。如果您无法使用具有真实域名的服务器进行测试,您可能需要为所有内容启用明文流量。

标签: android http


【解决方案1】:

如果只是为了学习,你可以尝试打电话

StrictMode.setVmPolicy(StrictMode.VmPolicy.LAX);

当您的应用程序/活动被创建时。在尝试调试 HTTP 请求时,这应该会减少运行时的麻烦。

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2021-03-10
    相关资源
    最近更新 更多