自己封装的最简单的post请求,废话不都说,看代码
1.添加依赖
compile 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
compile 'com.google.code.gson:gson:2.8.0'
2.网络权限,自己添加吧。
3.post封装
public class PostUtils { private static JSONObject jsonObject; private static RequestQueue requestQueue; private static JsonObjectRequest jsonRequest; public static void initpost(Context context, Map<String, Object> prams, String url, final VolleyCallback callback) { if (requestQueue == null) { requestQueue = Volley.newRequestQueue(context.getApplicationContext()); } jsonObject = new JSONObject(prams); jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { JSONObject result = response; callback.onSuccess(result); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.onError(); } }) { @Override public Map<String, String> getHeaders() { HashMap<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json");
//有的接口请求需要token和userid,自己添加 // headers.put("appType", "20"); // headers.put("token", “”); // headers.put("uid", SharePrefManager.getUserId()); // headers.put("ticket", SharePrefManager.getToken2()); return headers; } }; requestQueue.add(jsonRequest); } /** * 成功请求接口 */ public interface VolleyCallback { void onSuccess(JSONObject result); void onError(); }
}4,项目中的使用
public void initData() {
//打印接口,自己封装一下方法吧
Logger.e("接口--" + UrlUtils.Url); Map<String, Object> prams = new HashMap<>(); prams.put("", "");//接口参数key--value PostUtils.initpost(getActivity(), prams, UrlUtils.rl, new PostUtils.VolleyCallback() { @Override public void onSuccess(JSONObject result) { Logger.e("post---" + result);//请求数据 String msg = result.toString(); Gson gson = new GsonBuilder().disableHtmlEscaping().create();
//gson数据转换
TrainBean commend = gson.fromJson(msg, TrainBean.class);//所有的数据都在commend里面,开始使用就可以了 } } @Override public void onError() { Logger. e( "post- --error"); } });
}