0

我需要从我自己的服务器中提取一个 GET 请求,以便从网络中提取,然后使用 TextView 显示在屏幕上。

我已经设置了一个 GET 请求。

public class GetMethodEx {


public String getInternetData() throws Exception{
        BufferedReader in = null;
        String data = null;
        try
        {
            HttpClient client = new DefaultHttpClient();
            URI website = new URI("http://www.mybringback.com");
            HttpGet request = new HttpGet();
            request.setURI(website);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in.readLine()) !=null){
                sb.append(l + nl);
            }
            in.close();
            data = sb.toString();
            return data;        
        } finally{
            if (in != null){
                try{
                    in.close();
                    return data;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
}

}

我已经在我的主线程上设置了提取信息并将其显示在文本视图中。

public class Home extends Activity {

    TextView httpStuff;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.httpexample);
        httpStuff = (TextView) findViewById(R.id.tvhttp);
        GetMethodEx test = new GetMethodEx();
        String returned;
        try {
            returned = test.getInternetData();
            httpStuff.setText(returned);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

但是,Textview 似乎没有改变?

有人能帮助我吗。

4

2 回答 2

1

安卓操作系统 > = 3.0

不允许NetworkRequest在主 UI 线程上。

使用AsyncTask调用 webrequest。

于 2012-11-30T17:32:02.943 回答
1

如果您想从 Ui Thread 进行任何网络操作,请使用AsyncTask更改您的代码:

public class Home extends Activity {

    TextView httpStuff;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.httpexample);
        httpStuff = (TextView) findViewById(R.id.tvhttp);
       new LongOperation().execute("");
    }
private class LongOperation extends AsyncTask<String, Void, String> {

      @Override
      protected String doInBackground(String... params) {
        GetMethodEx test = new GetMethodEx();
        String returned;
        try {
            returned = test.getInternetData();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            return returned;
      }      

      @Override
      protected void onPostExecute(String result) {    
        // Update Ui here    
         httpStuff.setText(result);       
      }

}

}

于 2012-11-30T17:32:19.713 回答