讨教用http://www.weather.com.cn/data/list3/city.xml获取城市的问题

Android 码拜 9年前 (2016-01-30) 1070次浏览
最近想做个天气的demo,用到了http://www.weather.com.cn/data/list3/city.xml,

    public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpsURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpsURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }

这样去获取但是报了java.lang.ClassCastException: com.android.okhttp.internal.http.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection这个错,本人已经有internet权限,不知道这是哪里的问题

解决方案:20分
url.openConnection()返回 的类型跟你定义的不一致啊,你要用相应的包才行

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明讨教用http://www.weather.com.cn/data/list3/city.xml获取城市的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)