带有POST的GsonRequest [英] GsonRequest with POST

查看:170
本文介绍了带有POST的GsonRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前正在使用的代码:

This is currently the code that I'm using:

/**
 * Volley adapter for JSON requests that will be parsed into Java objects by Gson.
 */
public class GsonRequest<T> extends Request<T> {
    private final Gson gson = new GsonBuilder()
            .registerTypeAdapter(ClusterUnits.class, new ClusterUnitsDeserializer()).create();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Listener<T> listener;
    private JSONObject parameters = null;

    /**
     * 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,
            Listener<T> listener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }

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

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

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> result = new HashMap<String, String>();
        try {
            result = new ObjectMapper().readValue(
                    parameters.toString(), TypeFactory.defaultInstance().constructMapLikeType(HashMap.class, String.class, String.class));
        } catch (IOException e) {
            DLog.d(e);
        }
        Log.i("PARAMETERS_LENGTH", String.valueOf(result.size()));
        return result;
    }

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

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data, HttpHeaderParser.parseCharset(response.headers));
            Log.i("RESPONSE", json);
            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));
        }
    }
}

发布数据是否正确?我用来执行HTTP请求,并使用GSON自动解码JSON.我继续收到错误消息,因为发布的参数不正确:(

Is it correct for posting data? I use to do HTTP requests and decode automatically the JSON with GSON. I continue to get errors because the params posted are not correct :(

推荐答案

我已经通过以下代码解决了该问题,即实现getBody并更改getBodyContentType:

I've solved the problem with the following code, i.e. implementing the getBody and changing the getBodyContentType:

    /**
     * Volley adapter for JSON requests that will be parsed into Java objects by Gson.
     */
    public class GsonRequest<T> extends Request<T> {
        private final Gson gson = new GsonBuilder()
                .registerTypeAdapter(ClusterUnits.class, new ClusterUnitsDeserializer()).create();
        private final Class<T> clazz;
        private final Map<String, String> headers;
        private final Listener<T> listener;
        private JSONObject parameters = null;

        /**
         * 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,
                Listener<T> listener, ErrorListener errorListener) {
            super(method, url, errorListener);
            this.clazz = clazz;
            this.headers = headers;
            this.listener = listener;
        }

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

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

        @Override
        public String getBodyContentType() {
            return "application/json";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return parameters.toString().getBytes(getParamsEncoding());
            } catch (UnsupportedEncodingException e) {
                DLog.d(e);
            }
            return null;
        }

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

        @Override
        protected Response<T> parseNetworkResponse(NetworkResponse response) {
            try {
                String json = new String(
                        response.data, HttpHeaderParser.parseCharset(response.headers));
                Log.i("RESPONSE", json);
                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));
            }
        }
    }

这篇关于带有POST的GsonRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆