最近想做个天气的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()返回 的类型跟你定义的不一致啊,你要用相应的包才行