带POST的GsonRequest

时间:2014-09-03 21:24:54

标签: android json gson android-volley

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

/**
 * 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。我继续得到错误,因为发布的参数不正确:(

2 个答案:

答案 0 :(得分:7)

您必须扩展JsonRequest。这是我的GsonRequest实现

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

答案 1 :(得分:1)

我用以下代码解决了这个问题,即实现了getBody并更改了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));
            }
        }
    }