从android中的URL网页获取String内容

时间:2013-08-11 18:34:43

标签: android string url download webpage

我有这个方法,助手说没有错误,但它只返回一个空字符串。我听说有一个DownloadFile变量类型,但我不想下载文件而是将其流式传输到字符串中。

public String getPage(String url){
    if (url.toLowerCase().startsWith("http") == false){
        url = "http://" + url;
    }
    URL fromstring = null;
    URLConnection openConnection = null;
    try {
        fromstring = new URL(url);
        openConnection = fromstring.openConnection();
        BufferedReader in = null;
        url = "";
        in = new BufferedReader(
            new InputStreamReader(
                openConnection.getInputStream()));
        String input = "";
        if (in != null) {
            while((input = in.readLine()) != null){
                url = url + input + "\r\n";
            }
            in.close();
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }
    return url;
}

这个也没用。

public String getPage(String url){
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    StringBuilder str = new StringBuilder();
    try {
        HttpResponse response = client.execute(request);
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null){
            str.append(line + "\r\n");
        }
        in.close();
    } catch (Exception e) {return null;}
    return str.toString();
}    

0 个答案:

没有答案