在使用JsonObjectRequest时无法post非json格式的数据,因而采用StringRequest获取到相应的数据后再转为json格式的数据。
//这里的上下文需要讨论 private static RequestQueue mRequestQueue = Volley.newRequestQueue(Global.getContext()); public interface IResponse{ void subscribeData(Object data); } /**Post方式从网络获取数据 */ public static void postDataFromNet(final IResponse iResponse, String url, final HashMap<String,String> map){ StringRequest request = new StringRequest( Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { iResponse.subscribeData(new JSONObject(response)); //将数据返回 } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.e("#StringRequest:Error#", volleyError.getMessage()); } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String,String> header = new HashMap<>(); header.put("token", "9FOYT495E6BCFLOKYE36F8C618533C3E"); return header; } @Override protected Map<String, String> getParams() throws AuthFailureError { return map; } }; request.setTag(""+url); mRequestQueue.add(request); }
时间: 2024-12-24 20:21:16