我一直在努力弄清楚如何读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();
}
}
}
}发布于 2014-03-25 00:49:23
我在问题中发布的代码有很多错误。下面是一个有用的例子:
public class GooglePlaces extends AsyncTask {
public InputStream inputStream;
public GooglePlaces(Context context) {
String url = "https://www.google.com";
try {
HttpRequest httpRequest = requestFactory.buildGetRequest(new GenericUrl(url));
HttpResponse httpResponse = httpRequest.execute();
inputStream = httpResponse.getContent();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
try {
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
Log.i("GooglePlacesTag", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}发布于 2014-03-21 16:53:53
您似乎没有连接您的HTTPUrlClient try con.connect()
https://stackoverflow.com/questions/22564552
复制相似问题