javaandroidrestandroid-studioandroidhttpclient

how to build REST client in android using HttpUrlConnection


I want to build an android app that consumes some REST APIs.

I'm using HttpURLConnection to make a basic authentication and GET/PUT some data, but I feel that I'm doing it the wrong way. I have a two classes ConnectionPUT and ConnectionGET that I call for every request, since each HttpURLConnection instance is used to make a single request.

What is the right way to build a REST client with Android using HttpURLConnection?


Solution

  • This is sample code for calling an Http GET using HttpUrlConnection in Android.

      URL url;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL("your-url-here");
    
            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();
    
    
    }    
        }
    

    But I strongly recommend that instead of re-inventing the wheel for creating a REST client for your android application, try the well-adapted and reliable libraries like Retrofit and Volley, for networking.

    They are highly reliable and tested, and remove all the boilerplate code you have to write for network communication.

    For more information, I suggest you to study the following article on Retrofit and Volley

    Android - Using Volley for Networking

    Android -Using Retrofit for Networking