使用 volley 在同一个 gson 请求中传递 header 和 Params

Pass header and Params in same gson request using volley

我正在尝试使用 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);

    }

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

...
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;
}

希望对您有所帮助!