网络框架Volley
生活随笔
收集整理的這篇文章主要介紹了
网络框架Volley
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Vollet 不是android自帶的框架 需要添加第三方的依賴? ?
? 注重? ? ??
implementation 'com.mcxiaoke.volley:library:1.0.19'? ? ? //Volley框架 依賴
1, 單例 + 請求隊列 -- 同步鎖
?????? ?2, get請求 -- 參數2個 -- 請求地址 , 請求成功的回調監聽器 -- StringRequest
?????? ?3, post請求 -- 參數3個 -- 請求地址, 請求參數, 請求成功的回調監聽器 -- JsonObjectRequest
?????? ?4, 網絡連接判斷 ???
? 封裝Volley? ?使用單例模式? ? ? ?
? 以下單獨創建的類 來請求數據
public class HttpUtils {private static RequestQueue requestQueue=null; 請求 隊列 單例模式private static HttpUtils httpUtils=null;private HttpUtils(){};public static HttpUtils getHttpUtils(Context context){if (httpUtils==null){synchronized (HttpUtils.class){ 安全鎖 if (httpUtils==null){requestQueue= Volley.newRequestQueue(context);httpUtils=new HttpUtils();}}}return httpUtils;}//GET請求的方法public void get(String path,Response.Listener listener){//4, 創建請求StringRequest request = new StringRequest(path, listener, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.e("TAG","獲取數據失敗!!!!");}});//TODO 5, 請求加入請求隊列requestQueue.add(request);}//POST請求的方法public void psot(String path,JSONObject params,Response.Listener listener){JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST, path, params, listener, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {System.out.println("數據獲取失敗");}}); // 請求加入請求隊列requestQueue.add(request);} }以下是在網絡數據請求的方法
POST
public void Http_user(View view) {//使用 map進行封裝 Map map =new HashMap();map.put("(對應字段)","(數據)");map.put("(對應字段)","(數據)");JSONObject jsonObject = new JSONObject(map);HttpUtils.getHttpUtils(MainActivity.this).psot("(網絡連接)", jsonObject, new Response.Listener() {@Overridepublic void onResponse(Object response) { // 獲取到的值 JSONObject json= (JSONObject) response;String message = json.optString("message");Toast.makeText(MainActivity.this, ""+message, Toast.LENGTH_SHORT).show();}});}GET
HttpUtils.getHttpUtils(MainActivity.this).get("(網絡連接) ", new Response.Listener() {@Overridepublic void onResponse(Object response) {String json = (String) response;textView.setText(json);}});}});?
總結
以上是生活随笔為你收集整理的网络框架Volley的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 道路测量xy坐标表示什么_UG NX后处
- 下一篇: 刚安装好CentOS 7,安装gtk3、