HttpHelper class for Android

When we are developing an application that is interacted with web, we needs http methods to get/put/post/delete something. For Android, i have created a helper class that is called as HttpHelper. Send url and json data to this class and receive meaningful response object with status, data and exception.

Example usage of this class :
String statusText = "";
String data = "";

// create http helper instance
HttpHelper httpHelper= new HttpHelper("http://www.google.com");
// execute get method
HttpResponseObject response = httpHelper.get();
// check exception in response
if (response.Ex == null) {
    // get status message
    statusText = response.StatusCode + " - " + response.StatusText;
    // get data
    BufferedReader reader = new BufferedReader(response.getDataReader());
    StringBuilder dataBuilder = new StringBuilder();
    String dataLine;
    try {
        while ((dataLine = reader.readLine()) != null) {
            dataBuilder.append(dataLine);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    data = dataBuilder.toString();
} else {
    // get error message
    statusText = "Error : " + response.Ex.toString();
}
// close connection
httpHelper.closeConnection();

Here is the list of functions in this helper class :

get() : Executes a http get request.
post() : Executes a http post request.
post(jsonData) : Executes a http post request with json data
put() : Executes a http put request.
put(jsonData) : Executes a http put request with json data
delete() : Executes a http delete request.


You can find source code and sample usage on

0 comments:

Post a Comment