HTTP Put set content type

2019-08-24 16:45发布

问题:

How can I set content type of HTTP Put as 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:

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

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

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:

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.

Thanks.

回答1:

Assuming you're using HTTPClient of 4.1.3 or greater -

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

There is a ContentType object which should be used to specify this.

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.

Example API call:

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

NOTE Editing for 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 entity not the execution (HttpPost or HttpPut) using setContentType(String). This is deprecated in 4.1.3 and beyond.