Android-Volley網絡通訊框架(StringRequest & JsonObjectRequest)

1.回想

       上篇對 Volley進行了簡介和對它的學習目的與目標,最後,爲學習Volley作了一些準備html


2.重點

      2.1 RequestQueue 請求隊列的創建java

      2.2 學習 StringRequest和JsonObjectRequest 。android


3.RequestQueue 請求隊列的創建

       新建類 volleyApplication 繼承自Application , 使用單例模式建立 請求處理隊列, 實現例如如下:json


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 對象app

           (2)設置參數:請求方式,URL地址,成功的返回調用。失敗的返回調用。ide

           (3)給請求設置 tag。加入到剛纔的請求隊列 中!
post

	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地址,成功的返回調用,失敗的返回調用;spa

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

相關文章
相關標籤/搜索