在Android中使用HttpURLConnection从url获取xml

我使用支持Apache HTTP客户端从url获取xml.

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, "UTF-8");

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

谷歌宣布从Android 6.0发布禁止支持Apache HTTP客户端,而是使用HttpURLConnection类.
最后,我想使用HttpURLConnection从url获取xml,但我不知道!有人可以帮帮我:)

最佳答案 作为一般提示,由于您没有触及它,我建议在IntentService中执行所有Web请求,这样它就不会阻止您的UI线程.至于答案,你可以像这样使用HttpURLConnection

public String getXMLFromUrl(String url) {
    BufferedReader br = null;
    try {
        HttpURLConnection conn = (HttpURLConnection)(new URL(url)).openConnection();
        br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String line;
        final StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }

        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (br != null) br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

它不应该太难理解,因为代码变化很小,但如果你有任何问题,我很乐意听到它们:)

点赞