Android-Volley網路通訊架構(StringRequest & JsonObjectRequest)

來源:互聯網
上載者:User

標籤:oid   請求方式   trre   cte   檔案的   對象   roi   自己   tracking   

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;

   

Android-Volley網路通訊架構(StringRequest &amp; JsonObjectRequest)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.