Content type text html charset utf 8 json

Understanding the Content-Type HTTP Header

The Content-Type header is used in web requests to indicate what type of media or resource is being used in the request or response. When you send data in a request such as PUT or POST, you pass the Content-Type header to tell the server what type of data it is receiving. When you receive a response from a server, there will be a Content-Type header as well. It tells the client what type of data is being returned so it knows how to process it.

Is Content-Type a required field?

Nope, Content-Type is not a required field. It’s not mandatory per the HTTP 1.1 specification. http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type «application/octet-stream».

Still, this can potentially cause problems and make it more difficult for the server to understand what it’s receiving from you. To avoid any issues down the road, I suggest you pass this header along regardless.

Is Content-Type case sensitive?

For your header field names, no. If you pass Content-Type or content-type or even something very creative like Content-TYPE . it should work fine! From http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2:

4.2 Message Headers HTTP header fields, which include general-header (section 4.5), request-header (section 5.3), response-header (section 6.2), and entity-header (section 7.1) fields, follow the same generic format as that given in Section 3.1 of RFC 822 [9]. Each header field consists of a name followed by a colon («:») and the field value. Field names are case-insensitive.

The parameter values you pass for this header can depend though. Generally, parameter values can be case sensitive and it depends on the value of the parameter. For example, the official W3C specs state «Names for character encodings are case-insensitive». So, a Content-Type: text/html; charset=UTF-8 should be equivalent to Content-Type: text/html; charset=utf-8 . These recommendations may also change so I advise using the proper casing from the start so you can relax and not have to worry.

Читайте также:  Php сохранить файл fopen

What is the difference between the Content-Type and Accept headers?

First, the Accept header is only used in requests (you probably won’t see it in responses), while the Content-Type is used in both requests and responses. This is because the Accept header is used in a request to tell the server what the type of media in the response should be. It’s like asking the server for information and telling it what kind of information you expect back. The Content-Type header tells you what the type of media in the current request actually is. It’s like sending the server a document that asks for information, and this header tells the server what type of document you gave them so they can read it properly.

Show me an example!

If I post an image to a website, my Content-Type header might be image/jpeg because the media in this request is a jpeg image. My Accept header would tell the website what kind of response I want back. If I don’t care, my Accept header would probably be */* which means anything works. When the website gets my post request with an image, I’ll get a response from them. It too will have a Content-Type header to tell me the type of their response. In this case, it is application/json;charset=utf-8 meaning their server responded with JSON.

What are the possible values of the Content-Type header?

Well, there’s a ton. Too many to list here, so I’ll cover the most common types which will probably have what you need. If you’re still curious though, here is the list of all Content-Type headers.

Text Types

  • text/xml
  • text/css
  • text/csv
  • text/html
  • text/plain
  • text/javascript

Images

  • image/gif
  • image/png
  • image/jpeg
  • image/svg+xml
  • image/tiff
  • image/x-icon
  • image/vnd.djvu

Application Types

  • application/zip
  • application/pdf
  • application/xml
  • application/ogg
  • application/json
  • application/ld+json
  • application/EDI-X12
  • application/EDIFACT
  • application/javascript
  • application/xhtml+xml
  • application/java-archive
  • application/octet-stream
  • application/x-shockwave-flash
  • application/x-www-form-urlencoded

Audio Types

Video Types

  • video/quicktime
  • video/webm
  • video/mpeg
  • video/mp4
  • video/x-flv
  • video/x-msvideo
  • video/x-ms-wmv

Multipart Types

These mean there are 2 or more pieces of content, each with their own type as well.

  • multipart/mixed
  • multipart/related
  • multipart/form-data
  • multipart/alternative

Источник

Content-Type Header

The Content-Type HTTP header is used to indicate the type of media in the body of the message.

For example, when you upload a PNG image to a website, the browser adds ‘Content-Type: image/png’ to the request header. When you send a JSON string, the browser will add ‘Content-Type: application/json’, for XML strings it will add ‘Content-Type: application/xml’, etc.

Читайте также:  What is java sound api

Below is an example of an HTTP request to send a JSON string to the server. The ‘Content-Type: application/json’ header tells the server that the request body contains a JSON string.

POST /echo/post/json HTTP/1.1 Accept: application/json Content-Type: application/json Content-Length: 16 Host: reqbin.com

When the server returns a JSON string, it indicates the data type with ‘Content-Type: application/json’ header.

HTTP/1.1 200 OK Content-Type: application/json Content-Length: 19

The Content-Type header has been added since HTTP 1.0. Setting this header is critical for both the request and the response and allows the client to control the way the server interprets the request. Properly used Content-Type headers help to avoid Content-Type Sniffing (or MIME Sniffing) attacks.

Syntax

The Content-Type header has a set of parameters that differs for the different types. Most parameters are applied only to certain content-types.

  • Content-Type: text/html; charset=utf-8
  • Content-Type: multipart/form-data; boundary=data_separator

Directives

  • Media-type: Multipurpose Internet Mail Extensions (MIME) type of the data.
  • Charset: character encoding in which the data will be received. The default charset is ISO-8859-1.
  • Boundary: required for multipart entities and is used to enclose the boundaries of the message parts.

Content-Type Header Examples

  • application/json
  • application/xml
  • application/zip
  • application/javascript
  • application/x-www-form-urlencoded
  • application/octet-stream
  • image/png
  • image/jpeg
  • image/svg+xml
  • image/x-icon
  • image/gif
  • text/html
  • text/css
  • text/plain
  • multipart/form-data
  • multipart/mixed
  • audio/mpeg
  • video/mp4
  • video/mpeg

Источник

What does «Content-type: application/json; charset=utf-8» really mean?

When I make a POST request with a JSON body to my REST service I include Content-type: application/json; charset=utf-8 in the message header. Without this header, I get an error from the service. I can also successfully use Content-type: application/json without the ;charset=utf-8 portion. What exactly does charset=utf-8 do ? I know it specifies the character encoding but the service works fine without it. Does this encoding limit the characters that can be in the message body?

Intriguingly, according to IANA’s application/json Media Type Registration, there doesn’t appear to be a supported charset parameter at all, albeit often being supplied in practice.

I know it specifies the character encoding but the service works fine without it. «working» does not always mean «the existent code/configuration is the most correct way covering all the corner cases to do one thing». It depends on all the conventions and assumptions which may not work under other circumstances. For me personally, I always try to be as explicit as possible.

JSON must be encoded by UTF-8, and there is no «charset» parameter. See this brief quote or have a look at RFC8259.

7 Answers 7

The header just denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can’t necessarily just look at the content and know what to do with it. That’s what HTTP headers are for, they tell the recipient what kind of content they’re (supposedly) dealing with.

Читайте также:  Php код отсчета времени

Content-type: application/json; charset=utf-8 designates the content to be in JSON format, encoded in the UTF-8 character encoding. Designating the encoding is somewhat redundant for JSON, since the default (only?) encoding for JSON is UTF-8. So in this case the receiving server apparently is happy knowing that it’s dealing with JSON and assumes that the encoding is UTF-8 by default, that’s why it works with or without the header.

Does this encoding limit the characters that can be in the message body?

No. You can send anything you want in the header and the body. But, if the two don’t match, you may get wrong results. If you specify in the header that the content is UTF-8 encoded but you’re actually sending Latin1 encoded content, the receiver may produce garbage data, trying to interpret Latin1 encoded data as UTF-8. If of course you specify that you’re sending Latin1 encoded data and you’re actually doing so, then yes, you’re limited to the 256 characters you can encode in Latin1.

Источник

Spring rest template cannot convert from text/html

Try something like that the default converters are not registered by default and an end user has to be explicit about registering the defaults :

@Configuration public class WebConfig extends WebMvcConfigurationSupport < @Bean public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() < MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); jsonConverter.setObjectMapper(objectMapper); return jsonConverter; >@Override public void configureMessageConverters(List> converters) < converters.add(customJackson2HttpMessageConverter()); super.addDefaultHttpMessageConverters(); >> 

Moreover please try fix type exception. Content type [text/html;charset=UTF-8] received from the service, the real content type should be application/json;charset=UTF-8

To get all ContentType you can do your custom converter like that:

List> messageConverters = new ArrayList>(); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList()); messageConverters.add(converter); restTemplate.setMessageConverters(messageConverters); 

Use RestTemplateBuilders to create the resttemplate clients. The builders will add the default Message converters.

Using solution above of user9709261 and Knight1128, I am adding the entire spring rest template from which I was able to consume an html response and get the status 200.

HttpHeaders headers = new HttpHeaders(); Charset utf8 = Charset.forName("UTF-8"); MediaType mediaType = new MediaType("text", "html", utf8); headers.setContentType(mediaType); HttpEntity httpEntity = new HttpEntity<>(postResponse, headers); UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(webhookURL); ApiUrl = new URI(builder.buildAndExpand(urlParams).toUri().toString()); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML)); restTemplate.getMessageConverters().add(converter); ResponseEntity objectResponseEntity = restTemplate.exchange(ApiUrl, HttpMethod.POST, httpEntity, String.class); Object body = objectResponseEntity.getBody(); return objectResponseEntity.getStatusCodeValue(); 

Источник

Оцените статью