Android中基於HTTP的通訊技術(5)Google開源庫 使用 Volley 實現 JSON 字串請求
阿新 • • 發佈:2019-01-07
使用 Volley 實現 JSON 字串請求,通過極少的程式碼以及更方便理解的引數完成通訊。
(來自極客學院的學習筆記,我是搬運工- -)
Volley是谷歌開發android平臺的網路通訊庫:更快,更簡單,更健壯。
volley提供的功能;
1.JSON,圖片(非同步)
2.快取
3.網路請求的排序
4.網路請求的優先順序處理
5.多級別的取消請求
6.與Activity生命週期聯動(螢幕翻轉)
package com.example.usingvolley; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getJSON(); } // 獲取JSON字串 public void getJSON(){ RequestQueue requestQueue = Volley.newRequestQueue(this); //獲取Volley的一個請求物件 String JSONDateUrl = "http://www.wwtliu.com/jsondata.html"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSONDateUrl, null, new Response.Listener<JSONObject>() { public void onResponse(JSONObject response) { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>response ="+ response); } },new Response.ErrorListener() { public void onErrorResponse(com.android.volley.VolleyError error) { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>.此資料頁有問題"); } } ); //(url, jsonRequest, listener, errorListener)=(請求方式,請求地址,監聽事件,錯誤的監聽事件),最後一個引數一次性寫完了兩個 requestQueue.add(jsonObjectRequest); } }
附上執行圖,因為沒有json格式的html網址,所以這裡返回了錯誤資訊,但是連線已經成功!