1

因此,我使用的是另一篇较早的帖子中的以下代码,但是其中一个部分遇到了问题,即:行HttpGet request = new HttpGet(url);不起作用。在 url 位置我放了类似的东西www.stackoverflow.com,但是那一部分不会让代码编译。我基本上是在尝试从 html 网站提取文本。完整代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(www.stackoverflow.com);
    HttpResponse response = client.execute(request);

    String html = "Toronto-GTA";
    InputStream in = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while((line = reader.readLine()) != null)
    {
        str.append(line);
    }
    in.close();
    html = str.toString();
}
4

4 回答 4

3

HTTPGet需要一个URL或字符串,因此请尝试将您的请求行更改为:

HttpGet request = new HttpGet("http://www.stackoverflow.com/");
于 2011-04-22T18:54:21.370 回答
2

使用以下形式的字符串:

[scheme:][//authority][path][?query][#fragment]

IE"http://www.stackoverflow.com"

于 2011-04-22T18:54:43.727 回答
0

尝试这个:HttpGet request = new HttpGet("www.stackoverflow.com");

于 2011-04-22T18:52:14.437 回答
0

在上面给出的答案中添加 try 和 catch 语句以捕获异常。

try{
HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("www.stackoverflow.com");
    HttpResponse response = client.execute(request);
    InputStream in = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line, html = null;
    while((line = reader.readLine()) != null)
    {
        str.append(line);
    }
    in.close();
    html = str.toString();
}
catch(Exception e){
//Do something here like printing the stacktrace
}
于 2011-04-22T19:19:23.337 回答