Android中基于HTTP的通信技术(5)Google开源库 使用 Volley 实现 JSON 字符串请求

来源:互联网 发布:hg的gp03d石斛兰淘宝 编辑:程序博客网 时间:2024/05/19 16:48

使用 Volley 实现 JSON 字符串请求,通过极少的代码以及更方便理解的参数完成通信。

(来自极客学院的学习笔记,我是搬运工- -)


  Volley是谷歌开发android平台的网络通信库:更快,更简单,更健壮。
  volley提供的功能;
  1.JSON,图片(异步)
  2.缓存
  3.网络请求的排序
  4.网络请求的优先级处理 
  5.多级别的取消请求 
  6.与Activity生命周期联动(屏幕翻转)

package com.example.usingvolley;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);getJSON();}// 获取JSON字符串public void getJSON(){RequestQueue requestQueue = Volley.newRequestQueue(this); //获取Volley的一个请求对象String JSONDateUrl = "http://www.wwtliu.com/jsondata.html";JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSONDateUrl, null, new Response.Listener<JSONObject>() {public void onResponse(JSONObject response) {System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>response ="+ response);}},new Response.ErrorListener() {public void onErrorResponse(com.android.volley.VolleyError error) {System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>.此数据页有问题");}});//(url, jsonRequest, listener, errorListener)=(请求方式,请求地址,监听事件,错误的监听事件),最后一个参数一次性写完了两个requestQueue.add(jsonObjectRequest);}}

附上运行图,因为没有json格式的html网址,所以这里返回了错误信息,但是连接已经成功!

Volley.jar下载地址

0 0