【问题标题】:Reading HttpURLConnection读取 HttpURLConnection
【发布时间】:2014-03-21 16:43:04
【问题描述】:

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

【问题讨论】:

  • 看看DavidWebb。在那里,您可以找到 HttpURLConnection 的抽象库和替代列表。 HttpURLConnection用起来太麻烦了,搜一下就知道了。
  • 看起来很有希望,今晚晚些时候我会试一试,并会报告。谢谢!

标签: java android bufferedreader httpurlconnection inputstreamreader


【解决方案1】:

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

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();
        }
    }
}

【讨论】:

    【解决方案2】:

    看来你没有连接你的 HTTPUrlClient 试试 con.connect()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多