Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Volley 異步網路請求完整示例(一):GET、POST 與 JSON

編輯:關於 Android 程式設計

Volley 的設計哲學是「把排隊、快取、重試、解碼這些瑣事都交給框架」。實際使用時,開發者只需要決定三件事:請求哪個網址、成功後怎麼處理、失敗後怎麼辦。

這個例子示範三種最常見的用法:GET 請求、POST 請求、JSON 請求。

MainActivity

package cc.cn;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

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.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends Activity {

    private RequestQueue mRequestQueue;
    private StringRequest mStringRequest;
    private JsonObjectRequest mJsonObjectRequest;
    private Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        volley_get();
        // volley_post();
        // volley_json();
    }

    /** GET 請求 */
    private void volley_get() {
        mContext = this;
        String url = "https://www.baidu.com/";

        // 1. 建立請求隊列
        mRequestQueue = Volley.newRequestQueue(mContext);

        // 2. 建立 StringRequest
        mStringRequest = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("請求結果:" + response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println("請求錯誤:" + error.toString());
                    }
                });

        // 3. 加入隊列,Volley 會自動安排背景執行
        mRequestQueue.add(mStringRequest);
    }

    /** POST 請求:覆寫 getParams 攜帶參數 */
    private void volley_post() {
        String url = "https://hxyj.cwwic.cn/wap/api_cs/user.php?action=login";
        mContext = this;
        mRequestQueue = Volley.newRequestQueue(mContext);

        mStringRequest = new StringRequest(
                Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("請求結果:" + response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println("請求錯誤:" + error.toString());
                    }
                }) {
            @Override
            protected HashMap<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("un", "411111222");
                hashMap.put("pw", "180034111");
                return hashMap;
            }
        };

        mRequestQueue.add(mStringRequest);
    }

    /** JSON 請求:直接拿到 JSONObject,不必自己解析字串 */
    private void volley_json() {
        mContext = this;
        String url = "https://m.weather.com.cn/data/101010100.html";
        mRequestQueue = Volley.newRequestQueue(mContext);

        mJsonObjectRequest = new JsonObjectRequest(url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println("請求結果:" + response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println("請求錯誤:" + error.toString());
                    }
                });

        mRequestQueue.add(mJsonObjectRequest);
    }
}

布局檔

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="學習 Volley(一)" />
</RelativeLayout>

幾個實務重點

RequestQueue 應該全域共用。上述範例為了示範方便每次都 Volley.newRequestQueue(),實際專案中應在 Application 或單例中建立一次並重複使用,否則每個頁面都會開一條背景線程與快取目錄。

回呼都在主線程。Volley 預設透過主線程的 Handler 分發結果,因此 onResponse 中可以直接更新 UI,不需要自己切線程。

記得取消。頁面離開時呼叫 mRequestQueue.cancelAll(...) 或對單一請求 cancel(),避免在已銷毀的 Activity 上更新介面。

前置條件同樣是引入 volley.jar 並加上網路權限 <uses-permission android:name="android.permission.INTERNET"/>。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved