Android - 如何使用Android 4.0下载XML文件?

时间:2012-11-04 15:34:25

标签: java android xml download

我将使用Android 4.0下载XML文件,我的旧代码在Android 2.3.3上运行:

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;
}

我有一个没有DefaultHttpClient的示例。 T.I.A。

2 个答案:

答案 0 :(得分:1)

从Gingerbread(2.3)开始,检索HTTP数据的首选方法是HttpUrlConnection。您可能需要查看this blog post以获取详细信息。您可能还想查看Javadoc for HttpUrlConnection

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
} finally {
    urlConnection.disconnect();
}

答案 1 :(得分:0)

你的问题可能就是“严格模式”。

您必须使用线程或AsyncTask执行http请求。

class RequestTask extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... params) {
             //http request here
            //return the response as string
        }
        @Override
        protected void onPostExecute(String result) {
            //set the the data you get
        }

然后:

new RequestTask().execute(yourHttpRequestString)