【发布时间】: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不是域,所以我认为您的方法行不通。如果您无法使用具有真实域名的服务器进行测试,您可能需要为所有内容启用明文流量。