0

我将使用 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 的示例。

4

2 回答 2

1

从 Gingerbread (2.3) 及更高版本开始,检索 HTTP 数据的首选方法是 HttpUrlConnection。您可能想查看此博客文章以了解详细信息。您可能还想查看HttpUrlConnection 的 Javadoc

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();
}
于 2012-11-04T20:35:17.213 回答
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)
于 2012-11-06T23:50:45.913 回答