Android Volley 發送JSON請求

JsonObjectRequest和JsonArrayRequest(均爲JsonRequest的子類),指定一個URL而且從響應中獲取JSON對象和數組。json

Volley提供如下類用於JSON 請求:數組

  • JsonArrayRequest - 該請求使用給定url,取回JSONArray響應體;
  • JsonObjectRequest - 該請求使用給定url,取回JSONObject響應體,容許一個可選的JSONObject做爲請求提的一個部分被髮送。

兩個class都以共同的類JsonRequest爲基類。下面的代碼段將獲取JSON返回,並將其顯示爲UI中的文本:ide

TextView mTxtDisplay;
ImageView mImageView;
mTxtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://my-json-feed";

JsonObjectRequest jsObjRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        mTxtDisplay.setText("Response: " + response.toString());
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub

    }
});

// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
相關文章
相關標籤/搜索