ANDROID Volley + Gson(POST)

时间:2016-04-05 16:35:12

标签: android android-volley gson

您好。

我想使用gson发布帖子请求。

我把这个类实现到了android网站...... http://developer.android.com/intl/pt-br/training/volley/request-custom.html

UserRequestHelper.userRequest(Request.Method.POST, EndpointURL.USUARIO, null, new Response.Listener<Usuario>() {
                    @Override
                    public void onResponse(Usuario response) {
                        Toast.makeText(getActivity(), "Cadastro realizado com sucesso!", Toast.LENGTH_SHORT).show();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), "Erro ao realizar cadastro.", Toast.LENGTH_SHORT).show();
                    }
                });

我需要一个机构来发送用户?我如何发送对象用户发帖请求?

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:3)

你必须覆盖getBody:

    @Override
public byte[] getBody() throws AuthFailureError {
    return gson.toJson(dataIn).getBytes();
}

编辑的整个示例类(形成相同的链接):

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 Response.Listener<T> listener;
private final Object dataIn;

/**
 * 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(String url, Object dataIn, Class<T> clazz, Map<String, String> headers,
                   Response.Listener<T> listener, Response.ErrorListener errorListener) {
    super(Method.POST, url, errorListener);
    this.dataIn = dataIn;
    this.clazz = clazz;
    this.headers = headers;
    this.listener = listener;
}

@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 byte[] getBody() throws AuthFailureError {
    return gson.toJson(dataIn).getBytes();
}

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