2011-09-22 73 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