java HTTP Put 设置内容类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14338997/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:55:58  来源:igfitidea点击:

HTTP Put set content type

javahttpcontent-typehttp-put

提问by dejoong

How can I set content type of HTTP Put as xxxx+xml?

如何将 HTTP Put 的内容类型设置为 xxxx+xml?

I was referring to solution in this link Android, sending XML via HTTP POST (SOAP). Its fine when we set content type like this, i mean the xml is came along with the request:

我指的是此链接Android 中的解决方案,通过 HTTP POST (SOAP) 发送 XML。当我们像这样设置内容类型时很好,我的意思是 xml 与请求一起出现:

httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");

but when i change type soapto something custom, the xml disappear on the request (i saw on the wireshark), like this:

但是当我将soap类型更改为自定义类型时,xml在请求中消失(我在wireshark上看到),如下所示:

httppost.setHeader("Content-Type","application/vnd.oma-pcc+xml;charset=UTF-8");

then, i tried put the xml only, so the request is ok again:

然后,我尝试只放 xml,所以请求又可以了:

httppost.setHeader("Content-Type","application/xml;charset=UTF-8");

I want to know what exactly the rules for the content-type than come together with the xml type so that the xml still there.

我想知道内容类型的确切规则是什么,而不是与 xml 类型结合在一起,以便 xml 仍然存在。

Thanks.

谢谢。

回答by Dave G

Assuming you're using HTTPClient of 4.1.3 or greater -

假设您使用的是 4.1.3 或更高版本的 HTTPClient -

When constructing you're entity, you have the option to specify the content being used for the POST or PUT operation for certain entities.

在构建实体时,您可以选择指定用于某些实体的 POST 或 PUT 操作的内容。

There is a ContentTypeobject which should be used to specify this.

应该使用一个ContentType对象来指定这一点。

Using the factory method .create() you can specify the mimetype with a charset - the ContentType will be used by the framework to properly emit the header in question.

使用工厂方法 .create() 您可以使用字符集指定 mimetype - 框架将使用 ContentType 来正确地发出有问题的标头。

Example API call:

示例 API 调用:

ContentType.create("application/vnd.oma-pcc+xml", CharSet.forName("UTF-8"));

ContentType.create("application/vnd.oma-pcc+xml", CharSet.forName("UTF-8"));

NOTE Editing for HttpClient 4.1.2

注意 HttpClient 4.1.2 的编辑

In the case of 4.1.2, when you create your entity for the post or put operation, set the content type on the entitynot the execution(HttpPost or HttpPut) using setContentType(String). This is deprecated in 4.1.3 and beyond.

在 4.1.2 的情况下,当您为 post 或 put 操作创建实体时,使用 setContentType(String)在实体上设置内容类型而不是执行(HttpPost 或 HttpPut)。这在 4.1.3 及更高版本中已弃用。