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

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;
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		queue=Volley.newRequestQueue(getApplicationContext());
	}
	
	//入口
	public static RequestQueue getQueue(){
		return queue;
	}
	
	
}

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

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		volleyApplication.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>() {

					@Override
					public void onResponse(String response) {
						// TODO Auto-generated method stub
						Toast.makeText(getApplicationContext(), response,
								Toast.LENGTH_SHORT).show();
						tv.setText(response);
					}
				}, new Response.ErrorListener() {

					@Override
					public 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>() {

			@Override
			public void onResponse(String response) {
				// 成功返回数据
				tv.setText(response);
			}
		},new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				//出错
				Toast.makeText(getApplicationContext(),
						error.getMessage(), Toast.LENGTH_SHORT).show();
			}
		}){
			@Override
			protected 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>() {

					@Override
					public 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 block
							tv.setText(e.getMessage());
						}
					}
				},new Response.ErrorListener() {

					@Override
					public 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 block
		e1.printStackTrace();
	}
	   
	   JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Method.POST,HttpPath.getSharedIfo_post()
			   ,jsonStr, new Listener<JSONObject>() {

				@Override
				public void onResponse(JSONObject response) {
					// TODO Auto-generated method stub
					JSONObject jsonObject;
					try {
						jsonObject = new JSONObject(response.getString("data"));
						tv.setText(jsonObject.getString("note"));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			},new Response.ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					// TODO Auto-generated method stub
					tv.setText(error.getMessage());
				}
			});
	   jsonObjectRequest.setTag("jsonPost");
	   volleyApplication.getQueue().add(jsonObjectRequest);
	   
	   
   }


6.JsonArrayRequest 

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

7. 注意 

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

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

   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值