You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中使用Jsoup提取用户公网IP遇Toast空白问题求助

Hey there! Let's troubleshoot why your Toast is coming up blank when trying to fetch that public IP. I’ve run into similar issues before, so here are the most likely fixes and a complete working example:

常见问题排查与解决步骤

1. 你可能忘了添加网络权限

Android requires explicit permission to access the internet. Add this line to your AndroidManifest.xml (outside the <application> tag):

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

Without this, your network request will silently fail, leaving no data to show in the Toast.

2. UI operations belong in the main thread

Your doit AsyncTask’s doInBackground method runs on a background thread—you can’t show a Toast from there. All UI updates (like Toast) must happen in the onPostExecute method, which runs on the main thread.

3. Network response parsing might be broken

If you’re not properly reading the response body or parsing the JSON, you’ll end up with a null/empty value. The target site returns {"ip":" current ip "}, so you’ll also want to trim the extra spaces around the IP string.

完整 Working Code

Here’s the full, corrected implementation of your AsyncTask:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_homepage);
    new FetchIpTask().execute(); // Renamed for better readability (Java convention)
}

private class FetchIpTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... voids) {
        String publicIp = null;
        try {
            // Replace with your target website URL
            URL url = new URL("https://your-target-ip-api.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000); // 5-second timeout
            connection.setReadTimeout(5000);

            // Read the response body
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream())
            );
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            connection.disconnect();

            // Parse the JSON response
            JSONObject json = new JSONObject(response.toString());
            publicIp = json.getString("ip").trim(); // Trim extra spaces

        } catch (Exception e) {
            e.printStackTrace(); // Log errors to debug what went wrong
        }
        return publicIp; // Pass result to onPostExecute
    }

    @Override
    protected void onPostExecute(String ip) {
        super.onPostExecute(ip);
        // This runs on the main thread—safe to show Toast here
        if (ip != null) {
            Toast.makeText(HomepageActivity.this, "Public IP: " + ip, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(HomepageActivity.this, "Failed to fetch IP", Toast.LENGTH_LONG).show();
        }
    }
}
Extra Tips
  • If your target site uses plain HTTP (not HTTPS) and your app targets Android 10+, add android:usesCleartextTraffic="true" to the <application> tag in AndroidManifest.xml to allow unencrypted requests.
  • For better network handling long-term, consider using modern libraries like OkHttp or Retrofit instead of HttpURLConnection—they simplify error handling and response parsing.

内容的提问来源于stack exchange,提问作者Calum Johnston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:55:39