我将使用 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 的示例。
最佳答案
从 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();
}
关于java - Android - 如何使用 Android 4.0 下载 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13219986/