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

Android Studio项目无法访问OpenWeather API URL的问题求助

问题:Android应用无法连接OpenWeather API URL

我想要在应用中使用OpenWeather API展示天气信息,但Android Studio无法连接目标URL,Logcat持续进入catch块的IO EXCEPTION分支。我已经在AndroidManifest.xml中添加了INTERNET和ACCESS_NETWORK_STATE权限,但问题仍未解决。

我的代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("JSON", "onCreate");
        DownloadWeatherData asyncTask = new DownloadWeatherData();
        asyncTask.execute("http://api.openweathermap.org/data/2.5/forecast?id=524901&appid=[APIkey]");
    }
    private class DownloadWeatherData extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            Log.d("JSON", "doInBackground");

            try{
                Log.d("JSON", strings[0]);

                URL REST = new URL(strings[0]);
                URLConnection connect = REST.openConnection();
                Log.d("JSON", connect.toString());
                InputStream stream = connect.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                StringBuilder builder = new StringBuilder();
                String line;
                while((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                String jsonString = builder.toString();
                JSONObject json = new JSONObject(jsonString);

                Log.d("JSON", jsonString);

            }catch(IOException e){
                e.printStackTrace();
                Log.d("JSON", "IO EXCEPTION");

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

已添加的权限:

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

修复方案

  • 改用HTTPS协议:OpenWeather API目前强制要求HTTPS连接,你的URL使用的是http://,替换为https://api.openweathermap.org/data/2.5/forecast?id=524901&appid=[你的API密钥]。Android 9(API 28)及以上版本默认禁止明文HTTP请求,这是触发IO异常的常见原因。

  • 验证API密钥有效性:确认[APIkey]已替换为你在OpenWeather官网申请的有效密钥,密钥错误会导致服务器返回401权限错误,进而触发IO异常。可以直接在浏览器中访问修改后的HTTPS URL,检查是否能返回正常的JSON数据。

  • 添加网络安全配置(仅当必须使用HTTP时):如果因特殊需求必须使用HTTP(不推荐),可在res/xml目录下创建network_security_config.xml文件:

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
    </network-security-config>
    

    然后在AndroidManifest.xml的<application>标签中添加:

    android:networkSecurityConfig="@xml/network_security_config"
    

    优先建议使用HTTPS,这是更安全的标准做法。

  • 替换AsyncTask(可选优化):AsyncTask已被官方废弃,推荐改用Coroutines、OkHttp或Retrofit等现代网络请求库,这些库处理网络请求更稳定,也更便于排查问题。例如使用OkHttp的示例:

    // 先在build.gradle中添加依赖
    // implementation 'com.squareup.okhttp3:okhttp:4.12.0'
    
    private void fetchWeatherData() {
        OkHttpClient client = new OkHttpClient();
        String url = "https://api.openweathermap.org/data/2.5/forecast?id=524901&appid=[你的API密钥]";
        Request request = new Request.Builder().url(url).build();
    
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
    
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String jsonString = response.body().string();
                    Log.d("JSON", jsonString);
                    // 解析JSON后需在主线程更新UI,可通过runOnUiThread实现
                }
            }
        });
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:55:17