Android-Volley网络通信框架(StringRequest & JsonObjectRequest)

来源:互联网 发布:网络博文怎么写 编辑:程序博客网 时间:2024/04/28 06:43

1.回顾

       上篇对 Volley进行了简单介绍和对它的学习目的与目标,最后,为学习Volley做了一些准备


2.重点

      2.1 RequestQueue 请求队列的建立

      2.2 学习 StringRequest和JsonObjectRequest ;


3.RequestQueue 请求队列的建立

       新建类 volleyApplication 继承自Application , 使用单例模式创建 请求处理队列, 实现如下:


package com.example.volleyHttp;import com.android.volley.RequestQueue;import com.android.volley.toolbox.Volley;import android.app.Application;public class volleyApplication extends Application {/** * 01. 建立  请求队列 * 02. 将 请求队列 加入到 AndroidMain.xml中 * 03.  */private static RequestQueue queue;@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();queue=Volley.newRequestQueue(getApplicationContext());}//入口public static RequestQueue getQueue(){return queue;}}

     这个可以与Activity 发生联动作用,在Activity 退出的时候,可以取消的 网络请求操作(通过 tag实现);下面可以实现:

@Overrideprotected void onStop() {// TODO Auto-generated method stubvolleyApplication.getQueue().cancelAll("strReqGet");super.onStop();}


      使用的时候需要在 AndroidMainfist.xml 文件里 的 Application 标签下 注册 刚才的 volleylication:

<application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"      <span style="color:#ff0000;">  android:name="com.example.volleyHttp.volleyApplication"</span>        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>

  不要忘记了添加网络权限!


4.StringRequest 的get和post方法

   

     4.1 get 操作

      (1)实例化StringRequest 对象

           (2)设置参数:请求方式,URL地址,成功的返回调用,失败的返回调用;

           (3)给请求设置 tag,添加到刚才的请求队列 中!

private void strRequest_get() {StringRequest request = new StringRequest(Method.GET,HttpPath.getSharedIfo(1), new Listener<String>() {@Overridepublic void onResponse(String response) {// TODO Auto-generated method stubToast.makeText(getApplicationContext(), response,Toast.LENGTH_SHORT).show();tv.setText(response);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_SHORT).show();}});request.setTag("strReqGet");<span style="color:#ff0000;">volleyApplication.getQueue().add(request);</span>}

      4.2 post 操作

           (1)实例化StringRequest 对象

           (2)设置参数:请求方式,URL地址,成功的返回调用,失败的返回调用;

           (3)Post提交的参数设置:重写 getParams 方法,返回Map集合,将自动调用;

           (4)请求设置 tag,添加到刚才的请求队列 中!


/** * 01.2 String Requset post 提交数据 */private void strRequest_post(){StringRequest stringRequest=new StringRequest(Method.POST,HttpPath.getSharedIfo_post(),new Listener<String>() {@Overridepublic void onResponse(String response) {// 成功返回数据tv.setText(response);}},new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {//出错Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_SHORT).show();}}){@Overrideprotected Map<String, String> getParams() throws AuthFailureError {// post 提交 重写参数 ,将自动 提交参数Map<String,String> map=new HashMap<String, String>();map.put("id","2");return map;}};stringRequest.setTag("strPost");volleyApplication.getQueue().add(stringRequest);}


5.JsonObjectRequest 的 get和post方法

     5.1 get 方法

           (1)实例化JsonObjectRequest 对象

           (2)设置参数:请求方式,URL地址,参数Jsonrequest 为 null (因为为get请求),成功的返回调用,失败的返回调用;

           (3)给请求设置 tag,添加到刚才的请求队列 中!

           (4)请求成功后,直接返回 成 JsonObject 对象 ,可以直接使用


/** * 02.jsonobjectRequert get请求 */private void jsonRequest_get(){JsonObjectRequest objectRequest=new JsonObjectRequest(Method.GET,HttpPath.getSharedIfo(1),null,new Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {//直接进行 json解析try {JSONObject jsonObject=new JSONObject(response.getString("data"));tv.setText(jsonObject.getString("note"));} catch (JSONException e) {// TODO Auto-generated catch blocktv.setText(e.getMessage());}}},new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {//请求失败返回的信息tv.setText(error.getMessage());}});objectRequest.setTag("jsonRequest");volleyApplication.getQueue().add(objectRequest);}

      5.2 post 方法

           (1)实例化JsonObjectRequest 对象

           (2)设置参数:请求方式,URL地址,参数JsonRequest ,成功的返回调用,失败的返回调用;

           (3)请求参数设置:通过 JsonObejct 实现 post提交 参数设置 (见示例代码)

           (4)给请求设置 tag,添加到刚才的请求队列 中!

           (5)请求成功后,直接返回 成 JsonObject 对象 ,可以直接使用

/** * 02.2 jsonObjectRequest post的方式 请求 */   private void jsonRequest_post(){     <span style="color:#ff0000;"> //封装请求参数 </span>   JSONObject jsonStr=new JSONObject();   try {jsonStr.put("id","2");} catch (JSONException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}      JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Method.POST,HttpPath.getSharedIfo_post()   ,jsonStr, new Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {// TODO Auto-generated method stubJSONObject jsonObject;try {jsonObject = new JSONObject(response.getString("data"));tv.setText(jsonObject.getString("note"));} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}},new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {// TODO Auto-generated method stubtv.setText(error.getMessage());}});   jsonObjectRequest.setTag("jsonPost");   volleyApplication.getQueue().add(jsonObjectRequest);         }


6.JsonArrayRequest 

    这个我就不在累赘了,和 JsonObjectResquest 一样 , 只不过返回的是 JsonArray 类型!

7. 注意 

    RequestQueue 请求队列 在初始化的时候,一定要在 android 配置文件的Application 标签里进行注册!

   使用的时候,注意 导入 包问题,ErrorListener 一定是 Response.ErrorListener;

   

0 0
原创粉丝点击