Android HTTP请求WiFi环境下失效,移动数据可正常运行
Hey there, let's work through this issue you're having! The fact that your request works on mobile data but fails on WiFi points to network-specific restrictions or configuration issues rather than your code itself. Let's break down the fixes step by step:
1. Verify WiFi Network Accessibility
First, rule out the simplest cause: is your WiFi network actually allowing access to Facebook?
- Open your phone's browser, connect to the same WiFi, and try loading
https://www.facebook.com/. If it fails to load, your WiFi is likely blocking the site (common in public/office networks with firewalls, or regions with DNS restrictions). - If the browser works but Jsoup doesn't, move to the next steps.
2. Increase Jsoup Timeout
Jsoup's default timeout is pretty short (3 seconds), which might not be enough for slower WiFi connections. Add a longer timeout to your request:
doc = Jsoup.connect("https://www.facebook.com/") .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6") .referrer("http://www.google.com") .timeout(10000) // 10 seconds timeout .get();
3. Check WiFi DNS Configuration
Faulty DNS settings on your WiFi can prevent domain resolution even if the network allows access. Try switching your WiFi's DNS to a public service like:
- Google DNS:
8.8.8.8/8.8.4.4 - Cloudflare DNS:
1.1.1.1/1.0.0.1
4. Confirm Manifest Permissions
Double-check that you've added the required internet permission in your AndroidManifest.xml (it's easy to typo this):
<uses-permission android:name="android.permission.INTERNET" />
Note: Since you're using HTTPS, you don't need extra configuration for cleartext traffic (that's only for HTTP requests on Android 9+).
5. Handle WiFi Proxy Settings
If your WiFi uses a proxy server, Jsoup won't automatically pick up the system proxy. You'll need to manually add it to your request:
// Replace with your WiFi proxy details doc = Jsoup.connect("https://www.facebook.com/") .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6") .referrer("http://www.google.com") .proxy("your-proxy-host", 8080) // Example proxy host and port .timeout(10000) .get();
Start with the first two steps—they're the most likely fixes for your SocketTimeoutException!
内容的提问来源于stack exchange,提问作者Andrei Nutu

