volley几种简单请求,GET+POST String+JSON

/**
 * 参见:http://blog.csdn.net/lfdfhl/article/details/12223345
 * 最近guolin写了几篇文章详细介绍Volley,所以在此比较系统地学习一下. 在本示例中,主要包括:
 * 1 利用Volley实现Get,Post请求
 * 2 利用Volley实现Json,Map数据请求
 * StringRequest
 * JsonRequest抽象类,无法实例,有两个直接的子类,JsonObjectRequest和JsonArrayRequest
 * 学习资料: http://blog.csdn.net/guolin_blog/article/details/17482095
 */
public class MainActivity extends Activity {
    private RequestQueue mRequestQueue;
    private StringRequest mStringRequest;
    private Context mContext;
    private JsonObjectRequest mJsonObjectRequest;
    private TextView text1, text2, text3, text4;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        text1 = (TextView) findViewById(R.id.text1);
        text2 = (TextView) findViewById(R.id.text2);
        text3 = (TextView) findViewById(R.id.text3);
        text4 = (TextView) findViewById(R.id.text4);
//        volley_StringRequest_GET();
        volley_StringRequest_POST();
        volley_JsonObjectRequest_POST();//JSONObject
//        volley_JsonObjectRequest_GET();
        jsonObjectPostRequest_POST_Map();//Map
    }


    /**
     * 利用StringRequest实现Get请求
     */
    private void volley_StringRequest_GET() {
        mContext = this;
        String url = "http://m.weather.com.cn/data/101010100.html";
        // 1 创建RequestQueue对象
        mRequestQueue = Volley.newRequestQueue(mContext);
        // 2 创建StringRequest对象
        mStringRequest = new StringRequest(url,
                new Response.Listener() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("Hanjh", "get请求结果:" + response);
                        text1.setText("get请求结果:" + response.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("Hanjh", "get请求错误:" + error.toString());
                text1.setText("get请求错误:" + error.toString());
            }
        }
        );
        // 3 将StringRequest添加到RequestQueue
        mRequestQueue.add(mStringRequest);
    }


    /**
     * 利用StringRequest实现Post请求
     */
    private void volley_StringRequest_POST() {
//        String url = "http://ave.bolyartech.com/params.php";
        String url = "http://demo.wanzi.cc/users/login";
        mContext = this;
        mRequestQueue = Volley.newRequestQueue(mContext);
        mStringRequest = new StringRequest(Method.POST, url,
                new Response.Listener() {
                    @Override
                    public void onResponse(String response) {
                        text2.setText("volley_post_StringRequest请求结果:" + response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                text2.setText("volley_post_StringRequest请求错误:"
                        + error.toString() + ",errorcode:"
                        + error.networkResponse.statusCode);
            }
        }
        ) {
            //携带参数,当发出POST请求的时候,Volley会尝试调用StringRequest的父类——
            // Request中的getParams()方法来获取POST参数
            @Override
            protected HashMap getParams()
                    throws AuthFailureError {
                HashMap hashMap = new HashMap();
//                hashMap.put("param1", "1");
//                hashMap.put("param2", "20");
                hashMap.put("user_password", "hanjiahu");
                hashMap.put("user_account", "8615161508006");
                return hashMap;
            }
        };
        mRequestQueue.add(mStringRequest);
    }


    /**
     * 利用JsonObjectRequest实现Post请求JSONObject
     */
    private void volley_JsonObjectRequest_POST() {
        String url = "http://ave.bolyartech.com/params.php";
        mContext = this;
        mRequestQueue = Volley.newRequestQueue(mContext);
        JSONObject object = new JSONObject();
        try {
            object.put("param1", "44");
            object.put("param2", "11");
            Log.i("Hanjhpost", "登录上传的信息" + object.toString());
            mJsonObjectRequest = new JsonObjectRequest(Method.POST, url,
                    object, createMyReqSuccessListener(),
                    createMyReqErrorListener());
            mRequestQueue.add(mJsonObjectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Response.Listener createMyReqSuccessListener() {
        return new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Log.i("Hanjh", "volley_post_JsonObjectRequest请求结果:"
                            + response);
                    text3.setText("volley_post_JsonObjectRequest请求结果:"
                            + response.toString());
                } catch (Exception e) {
                    text3.setText("Parse error");
                }
            }
        };
    }


    private Response.ErrorListener createMyReqErrorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (null != error) {
                    Log.i("Hanjh",
                            "volley_post_JsonObjectRequest请求错误:" + error.toString()
                    );
                    text3.setText("volley_post_JsonObjectRequest请求错误:" + error.toString());
                }
            }
        };
    }




    /**
     * 利用JsonObjectRequest实现GET数据请求
     */
    private void volley_JsonObjectRequest_GET() {
        mContext = this;
        String url = "http://m.weather.com.cn/data/101010100.html";
        // 1 创建RequestQueue对象
        mRequestQueue = Volley.newRequestQueue(mContext);
        JSONObject object = new JSONObject();
        try {
            object.put("user_password", "hanjiahu");
            object.put("user_account", "8615161508006");
            // 2 创建JsonObjectRequest对象
            mJsonObjectRequest = new JsonObjectRequest(Method.GET, url, null,
                    new Response.Listener() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.i("Hanjh_json", "json请求结果:" + response);
                            text4.setText("json请求结果:" + response.toString()
                            );
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("Hanjh_json", "json请求错误:" + error.toString());
                    text4.setText("json请求错误:" + error.toString());
                }
            }
            );
            // 3 将JsonObjectRequest添加到RequestQueue
            mRequestQueue.add(mJsonObjectRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }




    /**
     * 使用post上传map格式的信息
     */
    private void jsonObjectPostRequest_POST_Map() {
        String url = "http://demo.wanzi.cc/users/login";
        HashMap mMap = new HashMap();
        mMap.put("user_password", "hanjiahu");
        mMap.put("user_account", "8615161508006");
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(url, new Response.Listener() {


            @Override
            public void onResponse(JSONObject response) {
                text4.setText(response.toString());
                Log.d("Hanjh", response.toString());
            }
        }, new Response.ErrorListener() {


            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
                Log.d("Hanjh", error.toString());
            }
        }, mMap);
        requestQueue.add(jsonObjectPostRequest);
    }
}

你可能感兴趣的:(Android)