在Android中使用HttpURLConnection从url获取xml

时间:2015-11-17 14:36:45

标签: android xml httpurlconnection

我使用支持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,但我不知道!有人可以帮助我:)。

3 个答案:

答案 0 :(得分:3)

作为一般提示,由于您没有触及它,我建议在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();
        }
    }
}

由于代码更改很少,所以不应该太难理解,但如果您有任何问题,我很乐意听到它们:)

答案 1 :(得分:0)

您可以尝试修改或使用此项,如下所示:

// Create a new UrlConnection
            URL postUrl = null;
            try {
                postUrl = new URL("Your Url");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            // Open the created connection to server.
            HttpURLConnection httpURLConnection = null;
            try {
                httpURLConnection = (HttpURLConnection) postUrl.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            // Set up the post parameters
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.setConnectTimeout(15000);

            try {
                httpURLConnection.setRequestMethod("POST or GET");
            } catch (ProtocolException e) {
                e.printStackTrace();
                // Server Error
                return false;
            }

            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Content-Type", "text/xml");

            OutputStream outputStream = null;

            try {
                outputStream = httpURLConnection.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            // Create a writer to write on the output stream.
            BufferedWriter writer = null;
            try {
                writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return false;
            }
            // Send the post request
            try {
                writer.write();
                writer.flush();
                writer.close();
                outputStream.close();
                httpURLConnection.connect();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            // Get response code
            int response = 0;

            try {
                response  = httpURLConnection.getResponseCode();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // Get the Response
            String responseData = "";
            if(response == HttpURLConnection.HTTP_OK){//Response is okay
                String line = "";
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                    while ((line=reader.readLine()) != null) {
                        responseData += line;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            else{
                // Server is down or webserver is changed.
                return false;
            }
            return true;

答案 2 :(得分:-1)

您可能需要包含一些额外的库

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

如果你使用android studio,它可以为你下载jar文件,只需使用Alt + Enter help