user3100088
user3100088

Reputation: 445

Extracting data from Json object by http GET

I am working on android app and I want to know how to get data from Json object by using http GET the (the http request url is APIary)

It's my first time to use Json and httpRequests so I don't know the syntax needed for this

That's my HttpRequest class I'm using :

public abstract class HttpRequest extends AsyncTask<String, String, String> {

private HttpClient httpClient;


private HttpRequestBase request;

private boolean hasError = false;

private String errorMessage = null;

private boolean hasBody = false;


private int statusCode;


public HttpRequest(){
    httpClient = new DefaultHttpClient();
}

/**
 * This method is called from the subclasses to pass the request method used to this class
 * @param request , The request class passed from the subclass
 */
void setMethod(HttpRequestBase request){
    this.request = request;
}

/**
 * Adds a header to the current request
 * @param header , header key
 * @param value , header value
 */
public void addHeader(String header,String value){
    this.request.addHeader(header, value);
}

/**
 * @return false if the status code was anything other than 2XX after executing the request , true otherwise
 */
public boolean hasError() {
    return hasError;
}

/**
 * A getter for the error message
 * @return String the error message returned from the request if any
 */
public String getErrorMessage() {
    return errorMessage;
}

/**
 * This is the method responsible for executing the request and handling the response
 * @return String , The response body , null in case of errors
 */
@Override
protected String doInBackground(String... args) {
    if(hasBody){
        this.request.addHeader("content-type", "application/json");
    }
    ResponseHandler<String> handler = new BasicResponseHandler();
    HttpResponse x = null;
    try{
        x = httpClient.execute(this.request);
        this.statusCode = x.getStatusLine().getStatusCode();            
        return handler.handleResponse(x);
    }catch(ClientProtocolException  e ){
        hasError = true;
        errorMessage = e.getMessage();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * A getter method for the status code
 * @return int , the status code of executing the request
 */
public int getStatusCode(){
    return this.statusCode;
}

/**
 * A setter method to set whether the request has a body or not , used between this class and its subclasses
 * @param hasBody boolean
 */
void setHasBody(boolean hasBody){
    this.hasBody = hasBody;
}
}

Upvotes: 0

Views: 1331

Answers (1)

JossVAMOS
JossVAMOS

Reputation: 310

I think this post can help you :

How to parse JSON in Android

Tell me if don't understand !

Upvotes: 1

Related Questions