Android调用Node.js接口遭遇Socket权限拒绝问题求助
Answer
Hey there! Let's fix that java.net.SocketException: Permission denied error you're hitting. This issue comes down to two key Android security restrictions your app isn't accounting for, so let's walk through the fixes step by step.
1. Add Internet Access Permission
Android doesn't let apps access the internet by default—you have to explicitly declare this permission in your AndroidManifest.xml. Open the file and add these lines outside the <application> tag (usually at the top):
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- Optional, but helps with network status checks -->
Without the INTERNET permission, Android will block all network requests from your app immediately.
2. Allow Plaintext HTTP Requests (Android 9+)
Your API uses http:// (unencrypted plaintext), and starting with Android Pie (API 28), the OS blocks these requests by default to enforce security. You have two simple ways to bypass this for your local API:
Option A: Use a Network Security Config
- Create a new directory
res/xmlin your project (if it doesn't exist). - Inside that directory, create
network_security_config.xmlwith this content:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
- Link this config to your app in
AndroidManifest.xmlby adding an attribute to the<application>tag:
<application ... android:networkSecurityConfig="@xml/network_security_config"> <!-- Your app components go here --> </application>
Option B: Directly Enable Cleartext Traffic
If you prefer not to create a separate config file, just add this attribute to your <application> tag in AndroidManifest.xml:
<application ... android:usesCleartextTraffic="true"> <!-- Your app components go here --> </application>
Extra Checks to Ensure Success
- Same Local Network: Make sure your Android device/emulator and the computer running your Node.js API are connected to the same WiFi network. Your API uses a local IP (
192.168.215.2), so they need to be on the same network to communicate. - Firewall Settings: Verify that your computer's firewall isn't blocking incoming requests on port 8000. You may need to allow your Node.js app through the firewall.
Once you've made these changes, rebuild and run your app. Your Volley request should now connect to your API successfully and return the same JSON you saw in Postman!
内容的提问来源于stack exchange,提问作者hossein

