解决安卓OkHttp报错java.net.SocketException socket failed EACCES (Permission denied)

文章目录

笔者报错时的运行环境:

  • OkHttp 4.11.0

  • Android Studio Flamingo | 2022.2.1

  • Android SDK 33

  • Gradle 8.0.1

  • JDK 17

最近笔者在安卓中使用 OkHttp 向本地服务器发送请求的时候,发生了如下报错。

java.net.SocketException: socket failed: EACCES (Permission denied)
at java.net.Socket.createImpl(Socket.java:492)
at java.net.Socket.getImpl(Socket.java:552)
at java.net.Socket.setSoTimeout(Socket.java:1180)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.kt:293)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:207)
at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:226)
at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:106)
at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:74)
at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:255)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)

原来这个报错是因为笔者忘记在安卓清单文件中为该应用开启网络权限,因此该请求被安卓阻止。

开启网络权限的办法也很简单。在应用清单文件 AndroidManifest.xml 中使用如下代码即可。

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

你可能感兴趣的:(疑难杂症,Java,Android,android,okhttp,java)