空体通过android Volley使用PUT方法发送

时间:2015-02-03 15:57:13

标签: java android android-volley put

我正在使用Volley从REST服务获取数据。所以有两种方法,一种是POST,它在服务器上创建一个对象,另一种是PUT,它基本上更新了同一个对象。我使用相同的代码来发出这些请求。我只是改变了在Volley中传递的方法。使用正文中发送的正确数据通过POST请求很好,但它遇到了PUT请求的问题,它在正文中随机发送数据。

我转移到Google建议的自定义Request对象,但它仍然无效。

    int method = Request.Method.POST;

    String objID = sharedPreferences.getString("objID", null);
    String Url = "/api_url";

    if (objID != null)
    {
        Url += objID + "/";
        method = Request.Method.PUT;
    }

    try
    {
        JSONObject objJSON = new JSONObject();
        objJSON.put("name", "new_name");
    }
    catch (JSONException e)
    {
        // Handle Execption
    }

    GsonRequest request = new GsonRequest<CustomObj>(method, Url, CustomObj.class,null, null, objJSON.toString(),
    new Response.Listener<CustomObj>()
    {
        @Override
        public void onResponse(CartObj cartObj)
        {
            // Handling Logic
        }
    }
    ,
    new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError volleyError)
        {
            // Handle Error   
        }
    });

    VolleySingleton.getInstance(this).addToRequestQueue(request);

GsonRequest是我的自定义类扩展请求对象

public class GsonRequest<T> extends Request<T>
{
    private final Gson gson = new Gson();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Listener<T> listener;
    private final Map<String, String> params;
    private final String body;
    private ErrorListener mErrorListener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url     URL of the request to make
     * @param clazz   Relevant class object, for Gson's reflection
     * @param headers Map of request headers
     */

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

    public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers, Map<String, String> params, Listener<T> listener, ErrorListener errorListener)
    {
        this(method, url, clazz, headers, params, null, listener, errorListener);
    }

    public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers, Listener<T> listener, ErrorListener errorListener)
    {
        this(method, url, clazz, headers, null, null, listener, errorListener);
    }

    @Override
    public byte[] getBody() throws AuthFailureError
    {
        return body != null ? body.getBytes() : super.getBody();
    }

    @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();
    }


    @Override
    protected void deliverResponse(T response)
    {
        listener.onResponse(response);
    }

    @Override
    public void deliverError(VolleyError error)
    {
        mErrorListener.onErrorResponse(error);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response)
    {
        try
        {
            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
        }
        catch (UnsupportedEncodingException e)
        {
            return Response.error(new ParseError(e));
        }
        catch (JsonSyntaxException e)
        {
            return Response.error(new ParseError(e));
        }
    }
}

我正在使用GSON来解析我的数据,而CustomObj是一个用于齐射的映射对象。

1 个答案:

答案 0 :(得分:0)

首先,请确保您构建的网址(检查objID不为空的位置)是否正确。

其次,您可以尝试使用字符集调用getBytes()方法。

在请求覆盖getBody()方法中:

@Override
public byte[] getBody() throws AuthFailureError {
    try {
        return body != null ? body.getBytes(getParamsEncoding()) : super.getBody();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return super.getBody();
}

希望这会有所帮助。

修改

您还可以尝试覆盖getBodyContentType()方法:

@Override
public String getBodyContentType() {
    return "application/json; charset=" + getParamsEncoding();
}