2015-05-14 58 views
1

我正在尝试发送Post请求,但没有成功。发布JsonObject与Volley

该库工作正常,我设法发送一些字符串请求,但带有JsonObject的Post不起作用。

String urlJsonReq = "https://api.parse.com/1/classes/GameScore"; 
    String tag_json_obj = "tag_json"; 

    JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST, 
      urlJsonReq, 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 
        Log.d("MyApp", response.toString()); 
       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        VolleyLog.d("MyApp", "Error: " + error.getMessage()); 
        // hide the progress dialog 
       } 
    }) { 
     @Override 
     protected Map<String, String> getParams() { 
      Map<String, String> params = new HashMap<String, String>(); 
      params.put("value1", "testValue1"); 
      params.put("value2", "testValue2"); 
      return params; 
     } 

     @Override 
     public Map<String, String> getHeaders() throws AuthFailureError { 
      HashMap<String, String> headers = new HashMap<String, String>(); 
      headers.put("X-Parse-REST-API-Key", "xxxxxxxxxxxx"); 
      headers.put("X-Parse-Application-Id", "xxxxxxxxxxx"); 
      return headers; 
     } 

     @Override 
     public String getBodyContentType() { 
      return "application/json"; 
     } 
    }; 

我不断收到错误。我在某处读过,但没有任何细节,凌空不能发送JsonObjects,只能接收。如果你想解决这个问题,你应该实现一个自定义的类,但我真的不知道我是否在这里犯了一个愚蠢的错误(这是可能的)。

你们知道吗?

谢谢你的时间。

回答

2

您可以发送JSONObject而不过滤getParams或getBodyContentType。例如这样的东西

JSONObject object = new JSONObject(); 
    JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() { 
     @Override 
     public void onResponse(JSONObject response) { 

     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 

     } 
    }); 

显然你可以覆盖头,如果你需要。

+0

谢谢安迪,工作得很好! =) –

+0

太棒了!很高兴我能帮上忙 :) –