HTTP Connection for Marshmallow or for API 23 plus


Aim :

This tutorial mainly aims to give the recommended way for doing the HTTP connection for new api changes after API 23.
As per the new changes Apache classes are removed from the API23 so this post gives one of the way by using HttpURLConnection class.


Topics Covered :

-How to make connection using URLCoonection classes
-Setting Properties
-Making request
-Getting the Response.
-Code Snippep



-How to make connection using URLCoonection classes:

Obtain the URL Connection by making URL.openconnection()

The stream can be called by URLConnection.getInputStream()

Use the Stream classes like inputStream or Buffer reader to read the stream


-Setting Properties
 Various Properties can be set in following way
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true); 
-Making request
   

URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://www.yoursite.com");

        urlConnection = (HttpURLConnection) url
                .openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            System.out.print(current);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }    
    }

wfrrsdfa





Post a Comment