gpt4 book ai didi

Android Volley 发布请求 header 未更改

转载 作者:行者123 更新时间:2023-11-29 14:18:30 26 4
gpt4 key购买 nike

我正在使用 Android Volley 库发送 POST 请求。而对于 POST 请求

  • header 是 Content-Type:application/json
  • 帖子正文是Json String

但无论如何,我要更改 Volley Request Header,它始终设置为 Content-Type:text/html。这给了我 400 Bad Request。这是我在 Volley

上执行 POST 请求的类(class)
public class GsonRequest<T> extends Request<T> {
private final Class<T> clazz;
private final Map<String, String> headers;
private final Listener<T> listener;
private Map<String, String> postParams;
private String postString = 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, Map<String, Object> params,
Listener<T> listener, ErrorListener errorListener) {
super(method, url, errorListener);

this.clazz = clazz;
this.headers = headers;
this.listener = listener;

if (method == Method.POST && params != null && params.size() > 0) {
setRetryPolicy(new DefaultRetryPolicy(12000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
postString = new GsonBuilder().create().toJson(params);
}

}

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

}

@Override
public byte[] getBody() throws AuthFailureError {

return postString != null ? postString.getBytes(Charset
.forName("UTF-8")) : super.getBody();
}

@Override
public String getBodyContentType() {
return postString !=null?"application/json; charset=utf-8":super.getBodyContentType();
}

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

T responses = new GsonBuilder().create().fromJson(json, clazz);
return Response.success(responses,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (Exception e) {
return Response.error(new ParseError(e));

}
}
}

知道我做错了什么。我已经用普通的 HttpPost 进行了测试,它从那里开始工作,但是在使用 Volley 时,我的 POST Header 永远不会改变。

最佳答案

我发现我必须覆盖 getBodyContentType() 才能使 Content-Type header 正确更新:

    public String getBodyContentType()
{
return "application/json; charset=utf-8";
}

这是我的问题,其中包含有关此问题的更多详细信息:

关于Android Volley 发布请求 header 未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24022554/

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