casaoui
casaoui

Reputation: 151

Getting xml from url with HttpURLConnection in Android

I use support Apache HTTP client for getting xml from url.

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

Google announce from Android 6.0 release the suppression of support for the Apache HTTP client and use the HttpURLConnection class instead. Finally, I want use HttpURLConnection for getting xml from url, but I don't know! Someone can help me :)

Upvotes: 4

Views: 3582

Answers (3)

Thijs Koppen
Thijs Koppen

Reputation: 335

As a general tip, since you didn't touch on it, I suggest doing all web requests in an IntentService so it doesn't block your UI thread. As for an answer, you can use the HttpURLConnection like this

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

It shouldn't be too hard to understand as the code-change is minimal, but if you have any question I'd love to hear them :)

Upvotes: 3

Sylwek845
Sylwek845

Reputation: 145

you may need to include some additional libs

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;

if you use android studio it can download the jar files for you, just use Alt+Enter help

Upvotes: -1

Orkun Kocyigit
Orkun Kocyigit

Reputation: 1147

You can try to modify or use this as your requirement follows:

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

Upvotes: 0

Related Questions