java POST 请求的内容类型标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7775907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Content Type header for POST request
提问by AndyAndroid
I have in Java (similar in other languages, problem should be language independent) a POST request I am sending to the server. The POST request contains only some POST parameters no body.
我在 Java 中(在其他语言中类似,问题应该与语言无关)我发送到服务器的 POST 请求。POST 请求只包含一些没有正文的 POST 参数。
I basically have this:
我基本上有这个:
postData = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode("Hymanychan", "UTF-8");
//HttpSessionToken.setRequestProperty("Content-Type", "application/xml");
OutputStream postContent = (OutputStream)HttpSessionToken.getOutputStream();
postContent.write(postData.getBytes("UTF-8"));
This works fine. The question is around the second line, a comment at the moment. Uncommenting this line ruins my code, okay my data is not XML so I can understand this. To some REST services you have to POST a whole XML document, but no POST parameters, something like this
这工作正常。问题围绕着第二行,即此刻的评论。取消注释这一行会破坏我的代码,好吧,我的数据不是 XML,所以我可以理解这一点。对于某些 REST 服务,您必须 POST 整个 XML 文档,但没有 POST 参数,例如
postData = "<xml> whatever xml structure here </xml>"
HttpSessionToken.setRequestProperty("Content-Type", "application/xml");
OutputStream postContent = (OutputStream)HttpSessionToken.getOutputStream();
postContent.write(postData.getBytes("UTF-8"));
This works too. The difference is the postData is now an XML and the content type is set.
这也有效。不同之处在于 postData 现在是一个 XML 并且设置了内容类型。
The question now is, what if a Service requires BOTH, POST parameters as in example 1 AND an xml body as in example 2. How would I do this? If that never happens, why doesn't it happen?
现在的问题是,如果服务需要示例 1 中的 POST 参数和示例 2 中的 xml 正文,该怎么办。我该怎么做?如果那永远不会发生,为什么不发生?
Thanks, A.
谢谢。
采纳答案by Jon Lin
You could do that as multipart/form-data so you can have mixed content in a single POST body. It's similar to multipart-mime, and each part can have its own content-type. Here's a previous stackoverflow answer for multipart form-data in Java: How can I make a multipart/form-data POST request using Java?
您可以将其作为 multipart/form-data 来执行,这样您就可以在单个 POST 正文中包含混合内容。它类似于 multipart-mime,每个部分都可以有自己的内容类型。这是 Java 中多部分表单数据的先前 stackoverflow 答案:如何使用 Java 发出多部分/表单数据 POST 请求?