【问题标题】:Android Volley Post with Map<String, Object> params (?)带有 Map<String, Object> 参数的 Android Volley Post (?)
【发布时间】:2014-04-23 17:22:29
【问题描述】:

我一直在尝试将我的 Credentials 课程从 Android 发布到 C#.Net 网络服务器。

Volley Post 方法接受如下参数:

@Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return parameters;
    }

getParams() 的返回类型是 Map&lt;String, String&gt;,但我需要 Map&lt;String, Object&gt; 将我的课程发送到 Web 服务器。我什至尝试将我的类转换为 json 字符串,例如:

@Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("credentials", new Gson().toJson(mCredentials, Credentials.class));
        return parameters;
    }

但它不起作用。当“credentials”参数为空时,服务器返回“Invalid Parameter”错误。

服务器端没有任何问题,因为我可以使用AsyncTask 做到这一点。我决定把我的请求变成Volley,但我被这个问题困住了。

有人有解决办法吗?

【问题讨论】:

标签: android android-volley


【解决方案1】:

这就是我的做法(注意:params 是一个 jsonobject,而不是地图):

 //fill params
 JSONObject params = new JSONObject();
 params.put("username", username);
 params.put("password", password);

 //create future request object
 RequestFuture<JSONObject> future = RequestFuture.newFuture();
 //create JsonObjectRequest
 JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, params, future, future);
 //add request to volley
 MyVolley.getRequestQueue().add(jsObjRequest);
 //pop request off when needed
 try {
            JSONObject response = future.get();//blocking code
            } catch (Exception e) {
            e.printStackTrace();
     }

【讨论】:

    【解决方案2】:

    如果您需要让您的包发送类似对象的东西,您可以将 JSONObject 放在 JSONObject 中。例如

    JSONObject outer = new JSONObject();
    JSONObject inner = new JSONObject();
    inner.put("first_name","James");
    inner.put("last_name","Bond");
    outer.put("person",inner);
    outer.put("id","1");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多