2017-07-13 100 views
0

我是新来发送帖子请求。我想发送一个json字符串形式的对象,我该如何去实际发送json本身?我有这个至今:如何使用volley在Android中使用JSON字符串发送发布请求?

try { 
    Gson gson = new Gson(); 
    objInString = gson.toJson(obj); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

//json request 
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
     Request.Method.POST, url, 
     new Response.Listener<JSONObject>(){ 

      @Override 
      public void onResponse(JSONObject response) { 
       Log.d(TAG, response.toString()); 
      } 
}, new Response.ErrorListener(){ 
    @Override 
    public void onErrorResponse(VolleyError error){ 
     VolleyLog.d(TAG, "Error: " + error.getMessage()); 
    } 
}) 
+0

做得一样'新JsonObjectRequest( Request.Method.POST,网址,objInString, 新Response.Listener (){'或'如果是objInString'字符串,则使用'新的JSONObject(objInString)' –

+0

@ρяσѕρєяK ,我的objInString是一个字符串,我要做什么代码? – DessertsAndStuff

回答

1

试试这个

RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); 

JsonObjectRequest jsonObjReq = new JsonObjectRequest(int method, String url, jsonRequest, 
    Listener<JSONObject> listener, ErrorListener errorListener) { 
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, 
      errorListener); 
} 

queue.add(jsObjRequest); 

如果你在字符串格式的数据是JSON兼容,然后将其转换为JSONObject的像下面

try { 
     JSONObject jsonRequest=new JSONObject(jsonString); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
+0

正是我在找什么,谢谢 – DessertsAndStuff

0

如果你只是想发送一个字符串,并将其作为参数添加到POST请求中。

Map<String, String> params = new HashMap<>(); 
params.put("json", someJsonString); 

JsonObjectRequest jsonObjReq = new JsonObjectRequest(
     Request.Method.POST, url, params, 
     new Response.Listener<JSONObject>(){ 

      @Override 
      public void onResponse(JSONObject response) { 
       Log.d(TAG, response.toString()); 
      } 
}, new Response.ErrorListener(){ 
    @Override 
    public void onErrorResponse(VolleyError error){ 
     VolleyLog.d(TAG, "Error: " + error.getMessage()); 
    } 
}); 

然后,您可以通过参数名称“json”检索服务器中的字符串。

相关问题