我一直在试图弄清楚如何阅读 HttpURLConnection。根据这个例子:http ://www.vogella.com/tutorials/AndroidNetworking/article.html ,下面的代码应该可以工作。但是, readStream 永远不会触发,而且我没有记录任何行。
我确实知道 InputStream 是通过缓冲区传递的,但对我来说,逻辑在 readStream 方法中分解,然后主要是空字符串“line”和 while 语句。那里到底发生了什么/应该发生什么,我将如何解决它?另外,为什么我必须在 Try 语句中创建 url?它返回一个未处理的异常;java.net.MalformedURLException。
提前致谢!
static String SendURL(){
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream (con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return ("Done");
}
static void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.i("Tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}