【问题标题】:How to send a post request with a JSON string in Android using volley?如何使用 volley 在 Android 中发送带有 JSON 字符串的发布请求?
【发布时间】:2017-07-13 15:37:01
【问题描述】:

我是发送帖子请求的新手。我想以 json 字符串的形式发送一个对象,我该如何实际发送 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());
    }
})

【问题讨论】:

  • 使用new JsonObjectRequest( Request.Method.POST, url, objInString, new Response.Listener&lt;JSONObject&gt;(){ 或者如果objInString 是字符串,则使用new JSONObject(objInString)
  • @ρяσѕρєяK,我的 objInString 是一个字符串,我该怎么做?

标签: android json post gson android-volley


【解决方案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();
    }

【讨论】:

    【解决方案2】:

    如果您只想发送一个字符串,请将其作为参数添加到 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”检索服务器中的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 2014-11-14
      • 2014-06-06
      • 2018-02-16
      • 2017-10-27
      相关资源
      最近更新 更多