查看: 604|回复: 0

[Android教程] volley JsonObjectRequest post请求

发表于 2018-2-4 10:15:09

注意:使用JsonObjectRequest或继承自JsonObjectRequest类的对象提交一个post请求时,如果有参数需要提交,就必须以JSONObject的json串方式提交.否则通过重写getParams()方法的方式提交不管用,getParams()方法中提交post参数只适用于Request对象。

直接上代码:第一部分是调用,第二部分是自定义

  1. JsonObjectRequestWithCookie
  2. private void uploadUserOp(String opType, String musicKey) throws AuthFailureError {
  3. Log.w("LOG","invoke uploadUserOp with "+ opType+" and "+musicKey);
  4. HashMap<String, String> opMap = new HashMap<String, String>();
  5. opMap.put("op", opType);
  6. opMap.put("key", musicKey);
  7. JSONObject opJsonObject = new JSONObject(opMap);
  8. JsonObjectRequestWithCookie jsonObjectRequestWithCookie = new JsonObjectRequestWithCookie(Constants.USER_HISTORY_URL,opJsonObject, new Response.Listener<JSONObject>() {
  9. @Override
  10. public void onResponse(JSONObject jsonObject) {
  11. Log.w("LOG","get response jsonObject from post user history"+jsonObject.toString());
  12. try {
  13. if(jsonObject.getString("status").equals("success")){
  14. Log.w("LOG", "post /api/use/history/ success");
  15. }
  16. else{
  17. Log.w("LOG", "post /api/use/history/ failure");
  18. }
  19. } catch (JSONException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. }, new Response.ErrorListener() {
  24. @Override
  25. public void onErrorResponse(VolleyError volleyError) {
  26. Log.w("LOG", "操作失败");
  27. }
  28. },opMap);
  29. jsonObjectRequestWithCookie.setCookie(localCookie);
  30. RequestManager.getRequestQueue().add(jsonObjectRequestWithCookie);
  31. }
复制代码
  1. import com.android.volley.Request;
  2. import com.android.volley.Response;
  3. import com.android.volley.toolbox.JsonObjectRequest;
  4. import org.json.JSONObject;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. /**
  8. * Created by lsc on 2014/12/24.
  9. */
  10. public class JsonObjectRequestWithCookie extends JsonObjectRequest {
  11. private Map<String, String> mHeaders = new HashMap<>();
  12. public JsonObjectRequestWithCookie(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener,Map<String,String> map) {
  13. super(Request.Method.POST, url, jsonRequest, listener, errorListener);
  14. }
  15. public JsonObjectRequestWithCookie(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener){
  16. super(url, jsonRequest, listener, errorListener);
  17. }
  18. //拿到客户端发起的http请求的Header
  19. @Override
  20. public Map<String, String> getHeaders() throws AuthFailureError {
  21. return mHeaders;
  22. }
  23. //发送请求时,往Header中添加cookie,可以一并发送
  24. public void setCookie(String cookie) throws AuthFailureError {
  25. mHeaders.put("User-Agent", "Android:1.0:2009chenqc@163.com");
  26. mHeaders.put("Cookie",cookie);
  27. }
  28. }
复制代码

更多类型的post解释,可参见:



回复

使用道具 举报