首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取HttpURLConnection

读取HttpURLConnection
EN

Stack Overflow用户
提问于 2014-03-21 16:43:04
回答 2查看 1.6K关注 0票数 0

我一直在努力弄清楚如何读HttpURLConnection。根据这个例子:http://www.vogella.com/tutorials/AndroidNetworking/article.html,下面的代码应该可以工作。但是,readStream从不触发,我也不会记录任何行。

我确实知道InputStream是通过缓冲区传递的,但是对我来说,逻辑在readStream方法中分解了,然后大部分是空字符串'line‘和while语句。那里到底发生了什么/应该发生什么,我如何才能解决它?另外,为什么我必须在Try语句中创建url?它返回一个未处理的异常;java.net.MalformedURLException。

提前感谢!

代码语言:javascript
复制
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();
            }
        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-25 00:49:23

我在问题中发布的代码有很多错误。下面是一个有用的例子:

代码语言:javascript
复制
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();
        }
    }
}
票数 0
EN

Stack Overflow用户

发布于 2014-03-21 16:53:53

您似乎没有连接您的HTTPUrlClient try con.connect()

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22564552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档