4、volley 官方教程-中標準請求的使用

文章摘要
1、Request JSON 類型的請求


英文文獻

一、標準的volley請求

  • StringRequest。
    指定URL并接收原始字符串作為響應。
  • JsonObjectRequest和JsonArrayRequest(JsonRequest的兩個子類)。
    指定URL并分別獲取JSON對象或數組。

如果您的預期響應是這些類型之一,則可能不需要實現自定義請求。也就是標準請求。

二、Request JSON

Volley為JSON請求提供了以下類:

  • JsonArrayRequest - 在給定URL檢索JSONArray響應正文的請求。
  • JsonObjectRequest - 在給定URL檢索JSONObject響應體的請求,允許將可選JSONObject作為請求體的一部分傳入。

這兩個類都是基于公共基類JsonRequest的。 您使用它們遵循與其他類型的請求相同的基本模式。 例如,此代碼段將獲取JSON Feed,并將其顯示為UI中的文本:

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

測試log:

07-26 17:39:49.788 D/hlwang  (32586): VolleySimpleRequest onResponse response is:{"data":{"yesterday":{"date":"25日星期二","high":"高溫 30℃","fx":"西南風","low":"低溫 22℃,"type":"陣雨"},"city":"北京","aqi":"35","forecast":[{"date":"26日星期三","high":"高溫 24℃","fengli":"微風級","low":"低溫 19℃","fengxiang":"北風","type":"小到中雨"},{"dat溫 28℃","fengli":"微風級","low":"低溫 23℃","fengxiang":"南風","type":"陰"},{"date":"28日星期五","high":"高溫 29℃","fengli":"微風級","low":"低溫 22℃","fengxiang":"南風","t日星期六","high":"高溫 29℃","fengli":"微風級","low":"低溫 20℃","fengxiang":"南風","type":"多云"},{"date":"30日星期天","high":"高溫 30℃","fengli":"微風級","low":"低溫 22℃"晴"}],"ganmao":"相對于今天將會出現大幅度降溫,易發生感冒,請注意適當增加衣服,加強自我防護避免感冒。","wendu":"23"},"status":200,"message":"OK"}

附:json api測試接口:1、sojson。2、bejson

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容