2011-04-22 59 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 
}