035 Android Volley框架進行網絡請求

1.volley入門介紹java

  開發Android應用的時候不可避免地都須要用到網絡技術,而多數狀況下應用程序都會使用HTTP協議來發送和接收網絡數據。Android系統中主要提供了兩種方式來進行HTTP通訊,HttpURLConnection和HttpClient,幾乎在任何項目的代碼中咱們都能看到這兩個類的身影,使用率很是高。android

  Volley但是說是把AsyncHttpClient和Universal-Image-Loader的優勢集於了一身,既能夠像AsyncHttpClient同樣很是簡單地進行HTTP通訊,也能夠像Universal-Image-Loader同樣輕鬆加載網絡上的圖片。除了簡單易用以外,Volley在性能方面也進行了大幅度的調整,它的設計目標就是很是適合去進行數據量不大,但通訊頻繁的網絡操做,而對於大數據量的網絡操做,好比說下載文件等,Volley的表現就會很是糟糕。git

下圖所示的這些應用都是屬於數據量不大,但網絡通訊頻繁的,所以很是適合使用Volleygithub


2.volley的使用環境配置web

(1)添加volley的依賴算法

github地址:https://github.com/mcxiaoke/android-volleyjson

implementation 'com.mcxiaoke.volley:library:1.0.19'

(2)聲明網絡權限緩存

//網絡權限,當禁用後,沒法進行檢索等相關業務
<uses-permission android:name="android.permission.INTERNET" />

3.StringRequest的用法服務器

(1)獲取到一個RequestQueue對象網絡

//取得請求隊列
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

  RequestQueue是一個請求隊列對象,它能夠緩存全部的HTTP請求,而後按照必定的算法併發地發出這些請求。RequestQueue內部的設計就是很是合適高併發的,所以咱們沒必要爲每一次HTTP請求都建立一個RequestQueue對象,這是很是浪費資源的,基本上在每個須要和網絡交互的Activity中建立一個RequestQueue對象就足夠了。
(2)建立一個StringRequest對象

(3)將這個StringRequest對象添加到RequestQueue裏面就能夠了

//將請求添加到隊列中
requestQueue.add(request);

 4.使用案例

package com.example.administrator.test66smartbeijing.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.administrator.test66smartbeijing.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

/**
 * 利用tabLayout+viewPager實現帶頂部菜單欄的fragment
 */
public class NewsCenterVolleyFragment extends Fragment {

    //handler用來處理消息
    @SuppressLint("HandlerLeak")
    Handler handler=new Handler(){
        @SuppressLint("ResourceType")
        @Override
        public void handleMessage(Message msg) {
            //更新ui
            if(msg.what==0x01){
                //接收到消息後,從當前的fragment跳轉到另外一個activity中
                String queryResultStr= (String) msg.obj;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDataFromServer();
        View view=inflater.inflate(R.layout.layout_fm_newscenter_volley,container,false);
        return view;

    }

    private void getDataFromServer() {
        //請求地址
        String url = "http://118.25.152.62:8080/SmartBeijingJavaWeb_war/JsonServlet";    //注①
        String tag = "BasicMessage";    //注②

        //取得請求隊列
        final RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

        //防止重複請求,因此先取消tag標識的請求隊列
        requestQueue.cancelAll(tag);

        //建立StringRequest,定義字符串請求的請求方式爲POST(省略第一個參數會默認爲GET方式)
        //一個StringRequest對象,StringRequest的構造函數須要傳入4個參數。
        // 第1個參數就是http請求的方式:Request.Method.POST,第2個參數就是目標服務器的URL地址:url。
        // 第3個參數是服務器響應成功的回調:new Response.Listener<String>(),第4個參數是服務器響應失敗的回調:new Response.ErrorListener()。
        final StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            String queryResultStr="";
                            //注意:當response爲空時,說明服務器無響應(服務器端的代碼有問題)
                            if(!TextUtils.isEmpty(response)){
                                JSONObject jsonObject = (JSONObject) new JSONObject(response).get("params");  //注③
                                queryResultStr=jsonObject.toString();
                                System.out.println(queryResultStr);


                                //當服務器鏈接成功,得到響應後,用Message對象傳遞消息,在Activity或fragment中處理。
                                Message message=new Message();//實例化message
                                message.what=0x01;//設置消息發送的驗證碼
                                message.obj=queryResultStr;//設置消息的內容
                                handler.sendMessage(message); //利用handler發送消息
                            }else {
                                Toast.makeText(getActivity(),"請求未響應",Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            //作本身的請求異常操做,如Toast提示(「無網絡鏈接」等)
                            Log.e("TAG", e.getMessage(), e);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //作本身的響應錯誤操做,如Toast提示(「請稍後重試」等)
                Log.e("TAG", error.getMessage(), error);
            }
        }) {
            //設置要提交給服務器的參數,若無需提交參數給服務器,能夠不重寫該方法
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //建立一個Map集合,用於存儲元素對(稱做「鍵」和「值」),其中每一個鍵映射到一個值
                Map<String, String> params = new HashMap<>();
                return params;
            }
        };

        //設置Tag標籤
        request.setTag(tag);

        //將請求添加到隊列中
        requestQueue.add(request);
    }


}

注意:url請求是用servlet,服務器端的javaweb必須採用servlet,即服務器和客戶端的請求要相互匹配。

5.控制檯輸出從服務器獲取的json數據。

System.out: {"Result":"{\"retcode\":200,\"data\":[{\"id\":10000,\"title\":\"新聞\",\"type\":1,\"children\":[{\"id\":10007,\"title\":\"北京\",\"type\":1,\"url\":\"\/10007\/list_1.json\"},{\"id\":10006,\"title\":\"中國\",\"type\":1,\"url\":\"\/10006\/list_1.json\"},{\"id\":10008,\"title\":\"國際\",\"type\":1,\"url\":\"\/10008\/list_1.json\"},{\"id\":10010,\"title\":\"體育\",\"type\":1,\"url\":\"\/10010\/list_1.json\"},{\"id\":10091,\"title\":\"生活\",\"type\":1,\"url\":\"\/10091\/list_1.json\"},{\"id\":10012,\"title\":\"旅遊\",\"type\":1,\"url\":\"\/10012\/list_1.json\"},{\"id\":10095,\"title\":\"科技\",\"type\":1,\"url\":\"\/10095\/list_1.json\"},{\"id\":10009,\"title\":\"軍事\",\"type\":1,\"url\":\"\/10009\/list_1.json\"},{\"id\":10093,\"title\":\"時尚\",\"type\":1,\"url\":\"\/10093\/list_1.json\"},{\"id\":10011,\"title\":\"財經\",\"type\":1,\"url\":\"\/10011\/list_1.json\"},{\"id\":10094,\"title\":\"育兒\",\"type\":1,\"url\":\"\/10094\/list_1.json\"},{\"id\":10105,\"title\":\"汽車\",\"type\":1,\"url\":\"\/10105\/list_1.json\"}]},{\"id\":10002,\"title\":\"專題\",\"type\":10,\"url\":\"\/10006\/list_1.json\",\"url1\":\"\/10007\/list1_1.json\"},{\"id\":10003,\"title\":\"組圖\",\"type\":2,\"url\":\"\/10008\/list_1.json\"},{\"id\":10004,\"title\":\"互動\",\"type\":3,\"excurl\":\"\",\"dayurl\":\"\",\"weekurl\":\"\"}],\"extend\":[10007,10006,10008,10014,10012,10091,10009,10010,10095]}"}

 參考文獻:https://blog.csdn.net/Mr_Megamind/article/details/71404618(很是經典)

相關文章
相關標籤/搜索