简体   繁体   中英

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?

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

REST client using HttpURLConnection

try {

        URL url = new URL("YOUR_URL");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));

        StringBuffer data= new StringBuffer(1024);
        String tmpdata="";
        while((tmpdata=reader.readLine())!=null) {              

               data.append(tmpdata).append("\n");

           }
        reader.close();

     }catch(Exception e){  
             e.printStackTrace();

        } finally {

         if (conn!= null) {
             conn.disconnect();

            } 

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM