以Volley第三方API輕鬆連接網際網路

在build.gradle引入使用


因為這是第三方的API, 可以透過build.gradle引入使用. 在 dependencies{...}中, 加上一列 implemention 'com.android.volley:volley:1.1.0' 即可.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    implementation 'com.android.volley:volley:1.1.0'

}							
    							

建立RequestQueue物件實體


透過呼叫Volley.newRequestQueue(Context)傳回RequestQueue物件實體. 用來處理請求物件的佇列, 因為可能會有多次的請求行為, 都可以透過這個物件來處理, 開發者毋須擔心請求的發送相關程序, 也就是簡化許多程序.

private RequestQueue queue;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    queue = Volley.newRequestQueue(this);
}
    							

開始發送GET的簡單請求


兩件事情要處理, 先建立StringRequest物件實體, 再將其add到之前所建立的RequestQueue物件中就可以了. 當然相關的連接網址以及回傳回來的資料, 都是在StringRequest中處理, 如下:

StringRequest stringRequest = new StringRequest(
        Request.Method.GET,
        "https://www.bradchao.com",
        new Response.Listener< String>() {
            @Override
            public void onResponse(String response) {
                Log.v("brad", response);
            }
        }, null);

queue.add(stringRequest);
            					

以GET方式傳遞參數


假設要傳遞的參數有account與passwd, 而其值分別為brad與1234, 則將會以?account=brad&passwd=123字串內容加在原來的網址後面.

StringRequest stringRequest = new StringRequest(
        Request.Method.GET,
        "https://www.bradchao.com/v2/apptest/getTest1.php?account=brad&passwd=1234",
        new Response.Listener< String>() {
            @Override
            public void onResponse(String response) {
                parseJSON(response);
            }
        }, null);

queue.add(stringRequest);    							
    							
上面的測試網址都可以提供網友進行測試, 而回傳資料格式為JSON. 所以附上解析JSON的範例程式如下:

private void parseJSON(String json){
    try {
        JSONObject root = new JSONObject(json);
        String result = root.getString("result");
        if (result.equals("success")){
            String lottery = root.getString("lottery");
            mesg.setText("OK:" + lottery);
        }else{
            mesg.setText("XX");
        }
    }catch (Exception e){
        Log.v("brad", e.toString());
    }
}								
								

以POST方式傳遞參數


假設要傳遞的參數有account與passwd, 而其值分別為brad與1234, 則必須以Override StringRequest的getParams()方法來處理.

StringRequest stringRequest = new StringRequest(
        Request.Method.POST,
        "https://www.bradchao.com/v2/apptest/postTest1.php",
        new Response.Listener< String>() {
            @Override
            public void onResponse(String response) {
                //Log.v("brad", response);
                parseJSON(response);
            }
        }, null){
    @Override
    protected Map< String, String> getParams() throws AuthFailureError {
        HashMap< String,String> params = new HashMap<>();
        params.put("account", "brad");
        params.put("passwd", "1234");
        return params;
    }
};

queue.add(stringRequest);    							
    							

將網路影像資料呈現在ImageView



String imgUrl = "http://www.bradchao.com/v2/img/book3.png";

ImageRequest imageRequest = new ImageRequest(imgUrl,
        new Response.Listener< Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                img.setImageBitmap(response);
            }
        },0,0,
        ImageView.ScaleType.CENTER,
        Bitmap.Config.ARGB_8888, null);

queue.add(imageRequest);    							
								

以Basic驗證取得API資料



StringRequest stringRequest = new StringRequest(
        Request.Method.GET,
        "https://www.bradchao.com/v2/apptest/authTest1.php",
        new Response.Listener< String>() {
            @Override
            public void onResponse(String response) {
                //parseJSON(response);
                Log.v("brad", response);
            }
        }, null){
    @Override
    public Map< String, String> getHeaders() throws AuthFailureError {
        String myAuth = "brad:1234";
        String myAuthBase64 = Base64.encodeToString(
                myAuth.getBytes(), Base64.NO_WRAP);
        HashMap< String,String> ret = new HashMap<>();
        ret.put("Authorization", "Basic " + myAuthBase64);
        return ret;
    }
};

queue.add(stringRequest);    							
								

以Toekn驗證取得API資料



StringRequest stringRequest = new StringRequest(
        Request.Method.GET,
        "https://www.bradchao.com/v2/apptest/authTest2.php",
        new Response.Listener< String>() {
            @Override
            public void onResponse(String response) {
                //parseJSON(response);
                Log.v("brad", response);
            }
        }, null){
    @Override
    public Map< String, String> getHeaders() throws AuthFailureError {
        String token = "123456";
        HashMap< String,String> ret = new HashMap<>();
        ret.put("Authorization", "Bearer " + token);
        return ret;
    }
};

queue.add(stringRequest);    							
								

Github: 原始碼