Volley中JsonObjectRequest的使用

package com.example.cuboo.myapplication;

import android.content.Context;
import android.util.Log;

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;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by cuboo on 2016/10/25.
 */

public class VolleyApi{
    private Context context;
    //步骤1:创建Volley的网络请求队列
    RequestQueue mQueue;
    //定义请求的URL
    private String url = "http://ditu.amap.com/service/regeo?longitude=121.04925573429551&latitude=31.315590522490712";
    public VolleyApi(Context context){
        this.context = context;
        mQueue = Volley.newRequestQueue(context);
    }

    /*
     *JsonObjectRequest不提交参数个服务器
     */
    public void getJsonData(){
        /*
         *步骤2:创建 JsonObjectRequest请求不给服务器提交参数
         */
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
                new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.d("TAG", jsonObject.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("TAG", volleyError.getMessage(), volleyError);
            }
        });
        //步骤3: JsonObjectRequest加入到队列中
        mQueue.add(jsonObjectRequest);
    }
    /*
    *JsonObjectRequest提交参数个服务器
    */
    public void getAndPutJsonData(){
           /*
         *步骤2:创建 JsonObjectRequest请求不给服务器提交参数
         */
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null,
                new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.d("TAG", jsonObject.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("TAG", volleyError.getMessage(), volleyError);
            }
        }){
            @Override
            protected Map getParams() throws AuthFailureError {
                Map map = new HashMap();
                map.put("userName", "value1");
                map.put("passWord", "value2");
                return map;
            }
        };
        //步骤3: JsonObjectRequest加入到队列中
        mQueue.add(jsonObjectRequest);
    }
}

你可能感兴趣的:(Android)