【问题标题】:Pass header and Params in same gson request using volley使用 volley 在同一个 gson 请求中传递标头和参数
【发布时间】:2015-10-09 12:38:29
【问题描述】:

我正在尝试使用 gson + volley 发出 PUT 请求,我必须在同一个请求中同时发送 Header 和 Params。我收到了成功响应,但没有将数据发送到服务器。我正在使用以下代码

public GsonRequest(int method,
                       String url,
                       Class<T> clazz,
                       Map<String, String> headers,
                       Map<String, String> params,
                       Listener<T> listener,
                       ErrorListener errorListener) {
        super(method, url, errorListener);
        this.clazz = clazz;
        this.params = params;
        this.listener = listener;
        this.headers = headers;
        mGson = new Gson();
    }

 @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return params != null ? params : super.getParams();
    }


@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return headers != null ? headers : super.getHeaders();
}

在 Activity 中我使用上面的 gson

private void updateProfile(String fname, String lname, String email, String mob) {

        String tag_json_obj = "json_obj_req";
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "JWT " + tinyDB.getString(Constants.MY_SHARED_PREF_TOKEN));
        Log.d("Authorization---", "JWT " + tinyDB.getString(Constants.MY_SHARED_PREF_TOKEN));
        String url = Constants.PATCH_USER+tinyDB.getString(Constants.MY_USER_ID);

        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-type", "application/x-www-form-urlencoded");
        params.put("first_name",fname);
        params.put("last_name",lname);
        params.put("email",email);
        params.put("mobile_no", mob);
//        url = url+"?first_name="+fname+"&last_name="+lname+"&email="+email+"&mob_no="+mob;
        Log.d("URL -- ", "" + url);
        GsonRequest<AddtoWishlistResponse> myReq = new GsonRequest<AddtoWishlistResponse>(
                Request.Method.PATCH,
                url,
                AddtoWishlistResponse.class,
                headers,
                params,
                createMyReqSuccessListener(),
                createMyReqErrorListener());
        AppController.getInstance().addToRequestQueue(myReq, tag_json_obj);

    }

【问题讨论】:

  • 尝试使用getBody() 而不是getParams()
  • @BNK 你应该定义一个方法 getBody 还是如何调用它?
  • 我已经添加了我的答案,但是,为什么你说make PUT request 但在代码中,你使用Request.Method.PATCH

标签: android gson android-volley


【解决方案1】:

您可以参考以下示例代码:

...
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers, String requestBody,
                   Response.Listener<T> listener, Response.ErrorListener errorListener) {
    super(method, url, errorListener);
    this.mClass = clazz;
    this.mHeaders = headers;
    this.mRequestBody = requestBody;
    this.mListener = listener;
    this.mErrorListener = errorListener;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return (mHeaders != null) ? mHeaders : super.getHeaders();
}

@Override
public String getBodyContentType() {
    return "application/json; charset=utf-8";
}

@Override
public byte[] getBody() throws AuthFailureError {
    try {
        return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
    } catch (UnsupportedEncodingException uee) {
        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                mRequestBody, "utf-8");
        return null;
    }
}

其他方法如parseNetworkResponse(), deliverResponse()...请参考this Google training documentation - Implementing a Custom Request

请求正文可以参考以下内容:

Map<String, String> stringMap = new HashMap<>();
stringMap.put("key1", "value1");
stringMap.put("key2", "value2");        
final String mRequestBody = buildRequestBody(stringMap);

...

private String buildRequestBody(Object content) {
    String output = null;
    if ((content instanceof String) ||
            (content instanceof JSONObject) ||
            (content instanceof JSONArray)) {
        output = content.toString();
    } else if (content instanceof Map) {
        Uri.Builder builder = new Uri.Builder();
        HashMap hashMap = (HashMap) content;
        if (hashMap != null) {
            Iterator entries = hashMap.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                entries.remove();
            }
            output = builder.build().getEncodedQuery();
        }
    }

    return output;
}

希望这会有所帮助!

【讨论】:

  • 我正在测试它会让你知道进一步的查询
  • 一个快速的问题,我将参数作为 Map 发送,我需要更改参数的 GsonRequest 方法吗?
  • 如果你使用HashMap,那么在getBodyContentType()里面的内容类型应该是application/x-www-form-urlencoded而不是application/json
  • 我再次检查了getBodyContentType()中的contentType,您可以根据服务器端的要求尝试application/x-www-form-urlencodedapplication/json。在我的项目中,我经常使用JSONObject 而不是HashMap :)
  • 感谢兄弟,经过几次修改,它现在可以工作了 快乐编码:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-06
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
相关资源
最近更新 更多