通过http GET从Json对象中提取数据

时间:2014-03-28 09:49:29

标签: java android json apache android-asynctask

我正在开发 android app ,我想通过使用http GET 知道如何从Json对象获取数据请求网址是APIary)

这是我第一次使用Json和httpRequests,所以我不知道这个所需的语法

这是我的HttpRequest课程,我正在使用:

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;
}
}

1 个答案:

答案 0 :(得分:1)

我认为这篇文章可以帮到你:

<强> How to parse JSON in Android

告诉我,如果不明白!