我怎么能在一个线程中做到这一点? [英] How I can do this in a thread ?

查看:75
本文介绍了我怎么能在一个线程中做到这一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想在线程中使用此代码<我怎么能这样做?

Hi I want to use this code in thread < How I can do this ??

public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

推荐答案

将其包装在 AsyncTask ;



Wrap it in an AsyncTask;

public class GetXmlTask extends AsyncTask<String, Void, String> {
     @Override
     protected String doInBackground(String...urls) {
         String url = urls[0]; // Might want to handle more here
         return getXmlFromUrl(url);
     }

     @Override
     protected void onPostExecute(String result) {
       // This runs on the ui thread when done, put your logic that works
       // on the result here
     }

     @Override
     protected void onPreExecute() {
     }

     @Override
     protected void onProgressUpdate(Void... values) {
     }

     private String getXmlFromUrl(String url) {
             String xml = null;

             try {
                 // defaultHttpClient
                 DefaultHttpClient httpClient = new DefaultHttpClient();
                 HttpPost httpPost = new HttpPost(url);

                 HttpResponse httpResponse = httpClient.execute(httpPost);
                 HttpEntity httpEntity = httpResponse.getEntity();
                 xml = EntityUtils.toString(httpEntity);

             }
             catch (UnsupportedEncodingException e) {
                 e.printStackTrace();
             }
             catch (ClientProtocolException e) {
                 e.printStackTrace();
             }
             catch (IOException e) {
                 e.printStackTrace();
             }
             // return XML
             return xml;
         }
 }





然后调用类似的新GetXmlTask​​( ).execute(http://google.com);



你可以得到有关 AsyncTask 的详细信息[ ^ ]。



希望这会有所帮助,

Fredrik



Then call that like new GetXmlTask().execute("http://google.com");.

You can get more details on AsyncTask[^].

Hope this helps,
Fredrik


这篇关于我怎么能在一个线程中做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆