2011-09-22 30 views
2

我想從網頁收集文本,將其放入字符串中,然後將其顯示在我的設備屏幕上。Android網絡請求字符串

這是我的WebRequest活動:

package com.work.webrequest; 

import java.io.IOException; 

import org.apache.http.HttpResponse; 
import org.apache.http.HttpStatus; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 

public class WebRequest extends Activity { 


    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     TextView txt = (TextView) findViewById(R.id.textView1); 
     txt.setText(getPage()); 
    } 

    private String getPage() { 
     String str = "***"; 

     try 
     { 
      HttpClient hc = new DefaultHttpClient(); 
      HttpPost post = new HttpPost("http://zapmenow.co.uk/zapme/?getDetails=true&secret=zjXvwX5frK1po0adXyKJsbbyUe2ZY2PkW9M8r7sb1soIDppIWdTlgt1xmL5VM6g&UDID=401ceca29af68e4569a25e8c16a6987bb8cf1f5a&id=41"); 

      HttpResponse rp = hc.execute(post); 

      if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
      { 
       str = EntityUtils.toString(rp.getEntity()); 
      } 
     }catch(IOException e){ 
      e.printStackTrace(); 
     } 

     return str; 
    } 


} 

main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<TextView android:layout_height="wrap_content" 
    android:id="@+id/textView1" 
    android:text="" 
    android:layout_width="wrap_content"></TextView> 
</LinearLayout> 

我沒有我的設備上在Eclipse中的任何錯誤,但應用程序崩潰。 請儘快幫助我; PS:我已經添加了線

​​ 清單中

,因此Internet權限是沒有問題的。

+0

你應該在這裏發表您logcat的輸出。由於應用程序崩潰,必須有堆棧跟蹤。 – Knickedi

回答

6

這是爲我工作的代碼:

private String getPage(String url) { 
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); 
    con.connect(); 

    if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { 
     return inputStreamToString(con.getInputStream()); 
    } else { 
     return null; 
    } 
} 

private String inputStreamToString(InputStream in) throws IOException { 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); 
    StringBuilder stringBuilder = new StringBuilder(); 
    String line = null; 

    while ((line = bufferedReader.readLine()) != null) { 
     stringBuilder.append(line + "\n"); 
    } 

    bufferedReader.close(); 
    return stringBuilder.toString(); 
} 

以後,你可以用它通過:

String response = getPage("http://example.com"); 
+0

**提示**:我有這段代碼就在我身邊,所以我把它給了你。在發佈問題前,您應該始終檢查您的logcat輸出。你不能爭論*沒有編譯錯誤,但它在設備上崩潰* – Knickedi