2011-04-22 68 views
1

所以我使用下面的代码从一个不同的旧帖子,但有一个部分的问题,行:HttpGet request = new HttpGet(url);不起作用。在url中,我放置了类似www.stackoverflow.com的东西,但是其中一部分不会让代码编译。我基本上试图从HTML网站拉文字。完整的代码:HttpGet无法识别url

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

for HttpGet request = new HttpGet(www.stackoverflow.com);我改成它(“www.stackoverflow.com”);正如许多人所建议的那样,但其他行如“HttpResponse response = client.execute(request);”返回编译错误,所有这些:未处理的异常类型IOException,eclipse中的大多数快速修复提示“Surroned with try/catch” – Clozecall 2011-04-22 19:08:16

回答

0

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

+0

我试着改变它,所以url有“”,但是这会导致如下行:“HttpResponse response = client.execute(request);“,”InputStream in = response.getEntity()。getContent();“,还有一些错误。 – Clozecall 2011-04-22 19:01:26

+0

“出错”是指编译错误还是运行时异常?如果是例外情况,请发布。 – djg 2011-04-22 19:03:25

+0

编译错误,所有这些:未处理的异常类型IOException,eclipse中的大多数快速修复提示“与try/catch一起使用Surroned” – Clozecall 2011-04-22 19:06:09

3

HTTPGet预计的URL或字符串,所以要尽量改变您的要求为:

HttpGet request = new HttpGet("http://www.stackoverflow.com/"); 
2

使用形式的字符串:

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

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

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 
}