我有个问题。这是我的代码:

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

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                xml = EntityUtils.toString(httpEntity);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).run();
    // return XML
    return xml;
}


那么,如何在我的线程中使用url以及如何返回xml?

谢谢您的帮助

最佳答案

Android提供了一个AsyncTask,非常适合您的目标。

例:

private class XMLTask extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        // Do stuff
        // For example showing a Dialog to give some feedback to the user.
    }

    @Override
    protected String doInBackground(.. parameters..) {
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            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;
    }

    @Override
    protected void onPostExecute(String xml) {
        // If you have created a Dialog, here is the place to dismiss it.
        // The `xml` that you returned will be passed to this method
        xml.Dowhateveryouwant

        }
    }
}

10-07 13:49