-
Notifications
You must be signed in to change notification settings - Fork 2
Using Android Request Classes
In order to facilitate creating HTTP requests in android , We've created some classes that will perform the request and get the response for you. Let's assume that we want to send a POST request to the endpoint : "http://entangle.io/user" to create a new user. The endpoint expects a JSON object of the following format :
{
"username" : "test",
"password" : "test2"
}
And the endpoint is expected to respond with status code 201 in case of success and 400 in case of failure and in case of success the endpoint will respond with the following JSON Object :
{
"message" : "Welcome test!"
}
To create this request in android it will look something like this :
// Grabbing the value of the variables
String username = "test";
String password = "test2";
// Creating the request body json object
JSONObject json = new JSONObject();
try {
json.put("username", username );
json.put("password", password );
} catch (JSONException e) {
e.printStackTrace();
}
//Creating a new Post Request
PostRequest request = new PostRequest("http://entangle.io/user"){
protected void onPostExecute(String response) { // On Post execute means after the execution of the request ( the callback )
if( this.getStatusCode() == 201 ){
viewSuccessMessage(response);
}else if( this.getStatusCode() == 400 ) {
showErrorMessage();
}
}
};
request.setBody(json); // Adding the json to the body of the request
request.addHeader("X", "Hi"); // Adding any additional header needed to the request
request.execute(); // Executing the request
After executing the request , the callback method we defined will be executed and the response body will be passed as a string to the callback method where we should parse it and extract the required data from it.