Android HTTP calls



Ivan Kocijan - ikocijan0@gmail.com

Milan Jovanović -milan.jovanovic24@gmail.com

Content

  • HTTP Requests
  • JSON
  • GSON
  • Retrofit

HTTP REQUESTS

  • Two ways
  • The right way
  • Better way :)

But first JSON

  • JSON - JavaScript Object Notation
{
 "firstName" : "Jopa",
 "lastName" : "Zeleni",
 "adress" : {
     "streetAddress" : "Vrbik 8",
     "city" : "Zagreb"
     },
  "phoneNumbers" : [
       "00/0000-000",
       "11/1111-111"
   ]
}

Then GSON

public class User {

@SerializedName("firstName")
private String firstName;

@SerializedName("lastName")
private String lastName;

.
.
.

}

Let's try to parse something

 {
     "stauts": 0,
     "response": {
         "gameStatus": 1,
         "question": {
             "text": "questionText",
             "answers": [
                 "answer 1",
                 "answer 2",
                 "answer 3",
                 "answer 4"
             ]
         }
      }
}

Our java models

public class ResponseGame {

    @SerializedName("stauts")
    private int responseStatus;
    
    @SerializedName("response")
    private Game game;

}
 {
     "stauts": 0,
     "response": {
         
      }
}

==

public class Game {

    @SerializedName("gameStatus")
    private int gameStatus;

    @SerializedName("question")
    private Question question;

    @SerializedName("treshold")
    private String treshold;
}

==

{

    "gameStatus": 1,
    "question": {
        "text": "questionText",
            "answers": [
               "answer 1",
               "answer 2",
               "answer 3",
               "answer 4"
            ]
    }

}
public class Question {
    
    @SerializedName("text")
    private String questionText;

    @SerializedName("answers")
    private ArrayList<String> answers;

}
{
    "text": "questionText",
        "answers": [
            "answer 1",
            "answer 2",
            "answer 3",
            "answer 4"
         ]
}

==

The right way for HTTP

BufferedReader in = null;
try {
    String url = "http://tvz.natjecanje.hr/smiley";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection)          
    obj.openConnection();
    con.setRequestMethod("GET");
    in = new BufferedReader(
    new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
        }
        
    } catch (IOException e) {
        //I think I should handle this exception
        e.printStackTrace();

    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                    //well at least I tried
            }}}

Practice

http://api.openweathermap.org/data/2.5/forecast?lat=45.811572&lon=15.952148

Retrofit

ApiManager.getRestService().getSmiley("smiley", smileyCallback);

Callback <SmileyResponse> smileyCallback = new CallBack<SmileyResponse> {
        @Override
        public void success(SmileyResponse response,Response response2) {
               //Woooohhhuuu
        }

        @Override
        public void failure (RetrofitError error) {
              //I failed
        }
    };

Setting up retrofit

public class APIManager {

    private static Mc2Service mc2Service;
    private static final String URL = "http://api.openweathermap.org/data/2.5";


    public interface Mc2Service {

        @GET("/forecast")
        void getWeatherInfo (@Query("lat") String latitude,
                             @Query("lon") String longitude,
                             Callback<ApiResponse> cb);
    }

    public static Mc2Service getApiService () {

        RestAdapter restAdapter = new RestAdapter.Builder().
                setEndpoint(URL).build();

        mc2Service = restAdapter.create(Mc2Service.class);


        return mc2Service;
    }
}

Weather API call with retrofit

    APIManager.getApiService().getWeatherInfo("45.811572", "15.952148",
                                               weatherCallback);


    private Callback<ApiResponse> weatherCallback = new Callback<ApiResponse>() {
        @Override
        public void success (ApiResponse weather, Response response) {
        }

        @Override
        public void failure (RetrofitError error) {
        }
    };

Practice

Homework

Examples from this workshop

Android HTTP calls - Workshop 3

By Ivan Kocijan Koc

Android HTTP calls - Workshop 3

Java HTTP calls, JSON, GSON, retrofit

  • 1,698