我正在使用Android Volley
库发送POST
请求。对于POST
请求
Content-Type:application/json
Json String
但无论如何,我要更改Volley Request Header
,它总是设置为Content-Type:text/html
。这给了我400 Bad Request
。这是我在POST
Volley
请求的课程
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
永远不会改变。
答案 0 :(得分:12)
我发现我必须覆盖getBodyContentType()
才能让Content-Type
标头正确更新:
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
以下是关于此问题的更多详细信息的问题:
答案 1 :(得分:8)
使用Wireshark
之类的网络嗅探工具,我发现我的错误位于错误的HTTP header
上。然后使用Chrome DHC plugin
我发现Header Content-Type
应为application/json; charset=utf-8
而且我一直在使用
Map<String, String> header = new HashMap<String, String>();
header.put("Content-Type", "application/json");
而不是
Map<String, String> header = new HashMap<String, String>();
header.put("Content-Type", "application/json; charset=utf-8");
使用正确的Header
解决了我的问题