gpt4 book ai didi

ANDROID Volley + Gson (POST)

转载 作者:搜寻专家 更新时间:2023-11-01 07:49:50 26 4
gpt4 key购买 nike

你好。

我想使用 gson 发出一个 post 请求。

我将类实现到 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();
}
});

我需要一个正文来发送给用户?我如何发送对象用户发出发布请求?

有人可以帮我吗?

最佳答案

你必须覆盖 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));
}
}
}

关于ANDROID Volley + Gson (POST),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36432152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com