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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容