Volley架構實現Http的get和post請求,volley架構getpost

來源:互聯網
上載者:User

Volley架構實現Http的get和post請求,volley架構getpost

一: volley簡介:

      Google I/O 2013上,Volley發布了。Volley是Android平台上的網路通訊庫,能使網路通訊更快,更簡單,更健壯。
這是Volley名稱的由來: a burst or emission of many things or a large amount at once

      volley適合於資料量比較小,比較頻繁的系統使用,可適用於各種管理平台,每次請求資料量小,但是請求頻繁的管理系統

簡化了安卓原生態的http請求方式。

二:volley的使用文法:

     1、使用volley前需要將volley的jar包匯入項目,jar包可在網上下載得到。

 

  2、volley的請求是通過RequestQueue 這個請求隊列來管理的,所以我們要在Application中給他定義一個RequestQueue,

     代碼如下:

package dao;import android.app.Application;import com.android.volley.RequestQueue;import com.android.volley.toolbox.Volley;public class MyApplication extends Application {    public static RequestQueue queue;    @Override    public void onCreate() {        super.onCreate();        queue = Volley.newRequestQueue(getApplicationContext());//使用全域上下文    }    public static RequestQueue getHttpQueue() {        return queue;    }}

  3: 使用volley發送一個get請求:

    StringReques request=new StringRequest(Method.GET,url,listener, errorlistener); StringRequest中Method指定請求方式是get還是post,url是請求的網路地            址,listener和errorlistener是一個回調方法參數,會分別返回請求成功和請求失敗的結果。

           執行個體代碼如下:

    

 1  1 package activity.cyq.com.lifecycle; 2  2  3  3 import android.app.Activity; 4  4 import android.os.Bundle; 5  5 import android.util.Log; 6  6 import android.widget.Toast; 7  7 import com.android.volley.AuthFailureError; 8  8 import com.android.volley.Request; 9  9 import com.android.volley.Response;10 10 import com.android.volley.VolleyError;11 11 import com.android.volley.toolbox.StringRequest;12 12 import java.util.HashMap;13 13 import java.util.Map;14 14 import dao.MyApplication;15 15 16 16 public class MainActivity2 extends Activity {17 17     private String cityname = "貴陽";18 18 19 19     @Override20 20     protected void onCreate(Bundle savedInstanceState) {21 21         super.onCreate(savedInstanceState);22 22         setContentView(R.layout.activity_main_activity2);23 23         volleyGet();24 24     }25 25 26 26     //volley發送get請求27 27     private void volleyGet() {28 28         String url = "http://apis.juhe.cn/idcard/index?key=bb97bfce9edee938aeac99cb503b76db&cardno=430524199106158690";29 29         StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {30 30             @Override31 31             public void onResponse(String s) {32 32                 Toast.makeText(MainActivity2.this, s, Toast.LENGTH_LONG).show();33 33                 Log.i("aa", "get請求成功" + s);34 34             }35 35         }, new Response.ErrorListener() {36 36             @Override37 37             public void onErrorResponse(VolleyError volleyError) {38 38                 Toast.makeText(MainActivity2.this, volleyError.toString(), Toast.LENGTH_LONG).show();39 39                 Log.i("aa", "get請求失敗" + volleyError.toString());40 40             }41 41         });42 42         //設定取消取消http請求標籤 Activity的生命週期中的onStiop()中調用43 43         request.setTag("volleyget");44 44         MyApplication.getHttpQueue().add(request);45 45     }46 46 }

     url為查詢一個城市的天氣的java資料,MyApplication.getHttpQueue().add(request);將request添加到請求隊列。

    volley個get請求過程就已經完成

4:volley的post請求:

    post請求和get請求大體一樣,只是多了一個參數傳遞的過程:

    StringRequest request=new StringRequest(Method.POST,url,listener,errorlistener){

        //實現Post參數的傳遞過程  

    }

    具體實現如下:

 1 //volley發送post請 2     private void volleypost() { 3         String url = "http://apis.juhe.cn/idcard/index?"; 4         StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { 5             @Override 6             public void onResponse(String s) { 7  8                 Log.i("aa", "post請求成功" + s); 9                 Toast.makeText(MainActivity2.this, s, Toast.LENGTH_LONG).show();10             }11         }, new Response.ErrorListener() {12             @Override13             public void onErrorResponse(VolleyError volleyError) {14                 Log.i("aa", "post請求失敗" + volleyError.toString());15                 Toast.makeText(MainActivity2.this, volleyError.toString(), Toast.LENGTH_LONG).show();16             }17         }) {18             @Override19             protected Map<String, String> getParams() throws AuthFailureError {20                 HashMap<String, String> map = new HashMap<>();21                 map.put("key", "bb97bfce9edee938aeac99cb503b76db");22                 map.put("cardno", "43052419910615");23                 return map;24             }25         };26         request.setTag("volleypost");27         MyApplication.getHttpQueue().add(request);28     }

    Google雖然沒給volley提供直接的參數傳遞的方法,但是他提供了getParams; volley是開源的網路請求架構,你完全可以根據自己的需求變更。

5:請求的登出:

    通過StringRquest().setTag("tagName");,我們給每一個請求設定了對應的標籤,可以再當前調用http請求的活動登出前,將包含的request也進行登出,

    避免不必要的資料請求,提高使用者體驗。

    方法如下:在生命週期的onStop()進行登出。

1  @Override2     protected void onStop() {3         super.onStop();4         MyApplication.getHttpQueue().cancelAll("volleyget"); //結束Activity時隊列裡面登出5         MyApplication.getHttpQueue().cancelAll("volleypost");6     }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.