標籤:android volley
簡介:
Volley是Google I/O 2013上Google官方發布的一款Android平台上的網路通訊庫。
以前的網路請求,要考慮開啟線程、記憶體流失、效能等等複雜的問題。但是Volley架構已經幫我們把這些問題處理好了,對外提供了相應的完善的請求API,我們只需要按照要求使用即可。
特點:
能使網路通訊更快,更簡單,更健壯
Get、Post網路請求及網狀圖像的高效率非同步處理請求
可以對網路請求進行排序優先順序管理
網路請求的緩衝
多層級取消請求
和Activity生命週期的聯動(Activity結束時同時取消所有網路請求)
使用Volley可以簡化一些網路通訊的開發,當然Volley不適合大資料(large payloads )和流媒體的網路請求。例如上百兆的檔案、視頻下載。
Volley開源,可以進行定製修改也可以直接使用Jar包的形式。
用法:
Volley的Get和Post請求方式的使用
Volley的網路請求隊列建立和取消隊列請求
建立請求首先建立隊列,將請求添加到請求隊列裡。
然後進行相應的Get和Post請求,請求結果在回調裡擷取解析。
Volley有自己的請求隊列管理機制,可以控制每個請求的建立與取消。非常方便和安全。
這樣也就可以做到隨時控制某個請求在什麼時候結束,Activity生命週期關聯,防止無謂的請求。
樣本:
首先我們需要選擇一個網路服務API,這裡我選擇彙總資料裡面的手機歸屬地查詢API,1註冊2申請,申請之後會為你的應用程式指派一個AppKey,下面是API說明:
/** * 介面地址:http://apis.juhe.cn/mobile/get支援格式:JSON/XML請求方式:GET/POST請求樣本:http://apis.juhe.cn/mobile/get?phone=13429667914&key=您申請的KEY請求參數: 名稱類型必填說明 phoneint是需要查詢的手機號碼或手機號碼前7位 keystring是應用APPKEY(應用詳細頁查詢) dtypestring否返回資料的格式,xml或json,預設json調用範例及調試工具: API測試載入器 返回欄位: 名稱類型說明 error_codeint返回碼 reasonstring返回說明 resultstring返回結果集 provincestring省份 citystring城市 areacodestring區號 zipstring郵編 companystring電訊廠商 cardstring卡類型JSON返回樣本:{"resultcode":"200","reason":"Return Successd!","result":{ "province":"浙江", "city":"杭州", "areacode":"0571", "zip":"310000", "company":"中國移動", "card":"移動動感地帶卡"}}XML返回樣本: <?xml version="1.0" encoding="utf-8" ?> - <root> <resultcode>200</resultcode> <reason>Return Successd!</reason> - <result> <province>浙江</province> <city>杭州</city> <areacode>0571</areacode> <zip>310000</zip> <company>中國移動</company> <card>移動動感地帶卡</card> </result> </root> * */
在使用Volley前,必須將jar包放入工程中去,我這裡寫了一個範例程式碼,如下:
public class MainActivity extends Activity implements OnClickListener{//聲明一個Volley請求隊列private RequestQueue requestQueue = null;//Get請求方式的URLprivate static final String URL_GET = "http://apis.juhe.cn/mobile/get?phone=18952201314&key=a53155cc6af64daabc66655b060db56a";//Post請求方式的URLprivate static final String URL_POST = "http://apis.juhe.cn/mobile/get?";//當前查詢的手機號碼歸屬地對象private PhoneAttribuion phoneAttribuion = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);setupViews();initVolleyRequest();}@Overrideprotected void onStop() {//當Activity介面已經停止的時候,取消掉所有的網路請求requestQueue.cancelAll("GET_TAG");requestQueue.cancelAll("POST_TAG");super.onStop();}@Overridepublic void onClick(View v) {int id = v.getId();switch (id) {case R.id.button1://當你點擊了Volley Get Request時volleyGet();break;case R.id.button2://當你點擊了Volley Post Request時volleyPost();break;default:break;}}private void setupViews(){findViewById(R.id.button1).setOnClickListener(this);findViewById(R.id.button2).setOnClickListener(this);}private void initVolleyRequest(){//初始化請求隊列requestQueue = Volley.newRequestQueue(this.getApplicationContext()); }//Get要求方法private void volleyGet(){//建立一個get請求,請求結果從回調方法onResponse()中獲得StringRequest stringRequest = new StringRequest(Method.GET, URL_GET, new Listener<String>() {@Overridepublic void onResponse(String arg0) {System.out.println("網路請求成功...");String result = arg0;System.out.println(result);//返回結果為json格式,如下格式://{// "resultcode":"200",//"reason":"Return Successd!",//"result":{"province":"江蘇","city":"徐州","areacode":"0516","zip":"221000","company":"中國電信","card":"中國電信天翼卡"},//"error_code":0//}//將結果封裝為對象try {//將結果String轉換成Json對象JSONObject ret = new JSONObject(result);//讀取resultcode值String resultCode = ret.getString("resultcode").trim();if("200".equals(result)){//請求結果正常JSONObject resultJson = ret.getJSONObject("result");//將所有的屬性值讀取出來String province = resultJson.getString("province");String city = resultJson.getString("city");String areaCode = resultJson.getString("areacode");String zip = resultJson.getString("zip");String company = resultJson.getString("company");String card = resultJson.getString("card");//建立一個手機歸屬地對象,將所有值封裝到phoneAttribuion對象中去phoneAttribuion = new PhoneAttribuion(province, city, areaCode,zip, company, card);//至此Get請求結束...}else{//請求結果異常System.out.println("請求結果異常...");}} catch (Exception e) {System.out.println(e);}}}, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {System.out.println("網路請求失敗...");}});//為此get請求設定一個Tag屬性stringRequest.setTag("GET_TAG");//將此get請求加入requestQueue.add(stringRequest);}private void volleyPost(){//建立一個post請求,請求結果從回調方法onResponse()中獲得StringRequest stringRequest = new StringRequest(Method.POST, URL_POST, new Listener<String>() {//重寫Listener的抽象方法@Overridepublic void onResponse(String arg0) {System.out.println("網路請求成功...");String result = arg0;System.out.println(result);//如果需要將結果封裝為PhoneAttribution對象,可參照Get方法中的方式,你也可以將該方式提取為業務方法,在這裡調用...}}, new ErrorListener() {//重寫ErrorListener的抽象方法@Overridepublic void onErrorResponse(VolleyError arg0) {System.out.println("網路請求失敗...");}}){//重寫StringRequest的抽象方法@Overrideprotected Map<String, String> getParams() throws AuthFailureError {Map<String, String> map = new HashMap<String, String>();map.put("phone", "18952201314");map.put("key", "a53155cc6af64daabc66655b060db56a");return map;}};//為此get請求設定一個Tag屬性stringRequest.setTag("POST_TAG");//將此get請求加入requestQueue.add(stringRequest);}}
代碼中用到了自己定義的一個實體類PhoneAttribution,內容如下:
<span style="font-family:SimSun;font-size:18px;">//手機號碼歸屬地類public class PhoneAttribuion {private String province; //省份private String city;//城市private String areaCode; //區號private String zip; //郵編private String company; //電訊廠商private String card; //卡套餐類型public PhoneAttribuion(String province, String city, String areaCode,String zip, String company, String card) {super();this.province = province;this.city = city;this.areaCode = areaCode;this.zip = zip;this.company = company;this.card = card;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getAreaCode() {return areaCode;}public void setAreaCode(String areaCode) {this.areaCode = areaCode;}public String getZip() {return zip;}public void setZip(String zip) {this.zip = zip;}public String getCompany() {return company;}public void setCompany(String company) {this.company = company;}public String getCard() {return card;}public void setCard(String card) {this.card = card;}}</span>
整個工程的代碼壓縮包如下,需要的可以下載:
Android Volley Demo
Android之Volley