GsonRequest with POST

我只是一个虾纸丫 提交于 2019-12-25 03:52:21

问题


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

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 :(


回答1:


You have to extend JsonRequest. Here is my GsonRequest implementation

public class GsonRequest<T> extends JsonRequest<T> {

private final Gson mGson;
private final Class<T> mClassType;
private final Map<String, String> mHeaders;
private final Response.Listener<T> mListener;

public GsonRequest(int method, String url, Class<T> classType, JSONObject jsonRequest,
                   Response.Listener<T> listener, Response.ErrorListener errorListener) {
    this(method, url, classType, null, jsonRequest, listener, errorListener);
}

public GsonRequest(int method, String url, Class<T> classType, Map<String, String> headers,
                   JSONObject jsonRequest, Response.Listener<T> listener,
                   Response.ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
            errorListener);
    mGson = new Gson();
    mClassType = classType;
    mHeaders = headers;
    mListener = listener;
}

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

@Override
protected Response<T> parseNetworkResponse(NetworkResponse networkResponse) {
    try {
        String json = new String(networkResponse.data, HttpHeaderParser.parseCharset
                (networkResponse.headers));
        return Response.success(mGson.fromJson(json, mClassType),
                HttpHeaderParser.parseCacheHeaders(networkResponse));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JsonSyntaxException e) {
        return Response.error(new ParseError(e));
    }
}

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



回答2:


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


来源:https://stackoverflow.com/questions/25653917/gsonrequest-with-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!