0

我一直在试图弄清楚如何阅读 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();
            }
        }
    }
}
4

2 回答 2

0

我在问题中发布的代码有很多问题。这是一个工作示例:

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-25T00:49:23.500 回答
-1

看来您没有连接 HTTPUrlClient 尝试 con.connect()

于 2014-03-21T16:53:53.383 回答