我正在尝试在 Volley 中编写一个 POST 调用,以将 XML 正文发送到服务器。我无法正确设置 Content-Type
header 。
基本的 StringRequest
看起来像这样:
StringRequest folderRequest =
new StringRequest(Method.POST, submitInterviewUrl, myListener, myErrorListener)
{
@Override
public byte[] getBody() throws AuthFailureError
{
String body = "some text";
try
{
return body.getBytes(getParamsEncoding());
}
catch (UnsupportedEncodingException uee)
{
throw new RuntimeException("Encoding not supported: "
+ getParamsEncoding(), uee);
}
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/xml");
return headers;
}
};
我覆盖 getHeaders()
以提供我想要的 Content-Type
header - application/xml
。
这是基于类似于这个的建议问题:
发送请求时,Volley 自动添加了第二个 Content-Type
header ,因此 header 如下所示:
Content-Type: application/xml
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
如何设置正确的标题?或删除不正确的标题?
我已尝试通过基本 Request
代码进行跟踪,但无法找到此额外 header 的来源。
最佳答案
Content-Type
header 的处理方式与 Volley 的其他 header 不同。特别是,覆盖 getHeaders()
以更改内容类型并不总是有效。
正确的做法是覆盖getBodyContentType()
:
public String getBodyContentType()
{
return "application/xml";
}
我通过查看 JsonRequest
类的代码发现了这一点。
Delyan 在他对这个相关问题的回答中也提到了这一点:
关于android - Volley 内容类型 header 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26246486/