Page contenttype text html charset

Кодировки и веб-страницы

Возвращаясь к избитой проблеме с кодировками русских букв, хотелось бы иметь под рукой некий единый справочник или руководство, в котором можно найти решения различных сходных ситуаций. В своё время сам перелопатил множество статей и публикаций, чтобы находить причины ошибок. Задача этой публикации — сэкономить время и нервы читателя и собрать воедино различные причины ошибок с кодировками в разработке на Java и JSP и способы их устранения.

Варианты решения могут быть не единственными, охотно добавлю предложенные читателем, если они будут рабочими.

Итак, поехали.

1. Проблема: при получении разработанной мной страницы браузером весь русский текст идёт краказябрами, даже тот, который забит статически.
Причина: браузер неверно определяет кодировку текста, потому что нет явного указания.
Решение: явно указать кодировку:
a) HTML: добавляем тэг META в хидер страницы:

[response.setCharacterEncoding("cp1251");] [response.setContentType("text/html;charset=cp1251");] 

2. Проблема: написанный в JSP-странице статический русский текст почему-то идёт краказабрами, хотя кодировка страницы задана.
Причина: статический текст был написан в кодировке, отличной от заданного странице.
Решение: изменить кодировку в редакторе (например, для AkelPad нажимаем «Сохранить как» и выбираем нужную кодировку).

3. Проблема: получаемый из запроса текст идёт кракозябрами.
Причина: кодировка запроса отличается от используемой для его обработки кодировки.
Решение: установить кодировку запроса или перекодировать в нужную.
а) Java, со стороны отправителя не задана нужная кодировка — перекодируем в нужную:

[String MyParam= new String(request.getParameter("MyParam").getBytes("ISO-8859-1"),"cp1251");] 

Примечание: кодировка ISO-8859-1 устанавливается по умолчанию, если не была задана другая.
б) Java, со стороны отправителя задана нужная кодировка — устанавливаем кодировку запроса:

[request.setCharacterEncoding("cp1251");] 

4. Проблема: отправленный GET-параметром русский текст при редиректе приходит кракозябрами.
Причина: упаковка русского текста в URI по умолчанию идёт в ISO-8859-1.
Решение: упаковать текст в нужной кодировке вручную.
а) JSP, URLEncoder:

Читайте также:  Синхронизация потоков java семафоры

5. Проблема: текст из базы данных читается кракозябрами.
Причина: кодировка текста, прочитанного из базы данных, отличается от кодировки страницы.
Решение: установить соответствующую кодировку страницы, либо перекодировать полученные из базы данных значения.
а) Java, перекодирование считанной в db_string базы данных строки:

[String MyValue = new String(db_string.getBytes("utf-8"),"cp1251");] 

6. Проблема: текст записывается в базу данных кракозябрами, хотя на странице отображается правильно.
Причина: кодировка записываемой строки отличается от кодировки сессии работы с базой данных, либо от кодировки базы данных (стоит помнить, что они не всегда совпадают).
Решение: установить необходимую кодировку сессии или перекодировать строку.
а) Java, перекодирование записываемой строки db_string в кодировку сессии или базы данных:

[String db_string = new String(MyValue.getBytes("cp1251"),"utf-8");] 
[dburl += "?characterEncoding=cp1251";] 
[connectionProperties="useUnicode=no;characterEncoding=cp1251;"] 

г) MySQL, прямая установка кодировки сессии вызовом SET NAMES (connect — объект подключения Connection):

[CallableStatement cs = connect.prepareCall("set names 'cp1251'"); cs.execute();] 

7. Проблема: если ничего не помогло…
Решение: всегда остаётся самый «топорный» метод — прямое перекодирование.
а) Для известной кодировки источника:
[String MyValue = new String(source_string.getBytes(«utf-8″),»cp1251»);]

б) Для параметра запроса:
[String MyValue = new String(request.getParameter(«MyParam»).getBytes(request.getCharacterEncoding()),»cp1251″);]

Дополнение, или что нужно знать:

1. Кодировки базы данных и сессии подключения могут различаться, в зависимости от конкретной СУБД и драйвера. К примеру, при подключении к MySQL стандартным драйвером com.mysql.jdbc.Driver без явного указания кодировка сессии устанавливалась в UTF-8, несмотря на другую кодировку схемы БД.
2. Кодировка упаковки строки запроса в URI по умолчанию устанавливается в ISO-8859-1. С подобным можно столкнуться, например, при передаче явно заданного текста в редиректе с одной страницы на другую.
3. Взаимоотношения кодировок страницы, базы данных, сессии, параметров запроса и ответа не зависят от языка разработки и описанные для Java функции имеют аналоги для PHP, Asp и других.

Примечание: восстановить ссылки на источники нет возможности, все примеры взяты из собственного кода, хотя когда-то так же выискивал их по многочисленным форумам.

Надеюсь, этот небольшой обзор поможет начинающим веб-программистам сократить время отладки и сберечь нервы.

Источник

Content-Type

The Content-Type representation header is used to indicate the original media type of the resource (prior to any content encoding applied for sending).

In responses, a Content-Type header provides the client with the actual content type of the returned content. This header’s value may be ignored, for example when browsers perform MIME sniffing; set the X-Content-Type-Options header value to nosniff to prevent this behavior.

In requests, (such as POST or PUT ), the client tells the server what type of data is actually sent.

Header type Representation header
Forbidden header name no
CORS-safelisted response header yes
CORS-safelisted request header yes, with the additional restriction that values can’t contain a CORS-unsafe request header byte: 0x00-0x1F (except 0x09 (HT)), «():<>?@[\]<> , and 0x7F (DEL).
It also needs to have a MIME type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded , multipart/form-data , or text/plain .

Syntax

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

Directives

The MIME type of the resource or the data.

The character encoding standard. Case insensitive, lowercase is preferred.

For multipart entities the boundary directive is required. The directive consists of 1 to 70 characters from a set of characters (and not ending with white space) known to be very robust through email gateways. It is used to encapsulate the boundaries of the multiple parts of the message. Often, the header boundary is prepended with two dashes and the final boundary has two dashes appended at the end.

Examples

Content-Type in HTML forms

In a POST request, resulting from an HTML form submission, the Content-Type of the request is specified by the enctype attribute on the element.

form action="/" method="post" enctype="multipart/form-data"> input type="text" name="description" value="some text" /> input type="file" name="myFile" /> button type="submit">Submitbutton> form> 

The request looks something like this (less interesting headers are omitted here):

POST /foo HTTP/1.1 Content-Length: 68137 Content-Type: multipart/form-data; boundary=---------------------------974767299852498929531610575 -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="description" some text -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="myFile"; filename="foo.txt" Content-Type: text/plain (content of the uploaded file foo.txt) -----------------------------974767299852498929531610575-- 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 10, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Setting the HTTP charset parameter

When a server sends a document to a user agent (eg. a browser) it also sends information in the Content-Type field of the accompanying HTTP header about what type of data format this is. This information is expressed using a MIME type label. This article provides a starting point for those needing to set the encoding information in the HTTP header.

The charset parameter

Documents transmitted with HTTP that are of type text, such as text/html, text/plain, etc., can send a charset parameter in the HTTP header to specify the character encoding of the document.

It is very important to always label Web documents explicitly. HTTP 1.1 says that the default charset is ISO-8859-1. But there are too many unlabeled documents in other encodings, so browsers use the reader’s preferred encoding when there is no explicit charset parameter.

The line in the HTTP header typically looks like this:

In theory, any character encoding that has been registered with IANA can be used, but there is no browser that understands all of them. The more widely a character encoding is used, the better the chance that a browser will understand it. A Unicode encoding such as UTF-8 is a good choice for a number of reasons.

Server setup

How to make the server send out appropriate charset information depends on the server. You will need the appropriate administrative rights to be able to change server settings.

Apache. This can be done via the AddCharset (Apache 1.3.10 and later) or AddType directives, for directories or individual resources (files). With AddDefaultCharset (Apache 1.3.12 and later), it is possible to set the default charset for a whole server. For more information, see the article on Setting ‘charset’ information in .htaccess.

Jigsaw. Use an indexer in JigAdmin to associate extensions with charsets, or set the charset directly on a resource.

IIS 5 and 6. In Internet Services Manager, right-click «Default Web Site» (or the site you want to configure) and go to «Properties» => «HTTP Headers» => «File Types. » => «New Type. «. Put in the extension you want to map, separately for each extension; IIS users will probably want to map .htm, .html. Then, for Content type, add » text/html;charset=utf-8 » (without the quotes; substitute your desired charset for utf-8; do not leave any spaces anywhere because IIS ignores all text after spaces). For IIS 4, you may have to use «HTTP Headers» => «Creating a Custom HTTP Header» if the above does not work.

Scripting the header

The appropriate header can also be set in server side scripting languages. For example:

Perl. Output the correct header before any part of the actual page. After the last header, use a double linebreak, e.g.:
print «Content-Type: text/html; charset=utf-8\n\n»;

Python. Use the same solution as for Perl (except that you don’t need a semicolon at the end).

PHP. Use the header() function before generating any content, e.g.:
header(‘Content-type: text/html; charset=utf-8’);

Java Servlets. Use the setContentType method on the ServletResponse before obtaining any object (Stream or Writer) used for output, e.g.:
resource.setContentType («text/html;charset=utf-8»);
If you use a Writer, the Servlet automatically takes care of the conversion from Java Strings to the encoding selected.

JSP. Use the page directive e.g.:

Output from out.println() or the expression elements ( ) is automatically converted to the encoding selected. Also, the page itself is interpreted as being in this encoding.

ASP and ASP.Net. ContentType and charset are set independently, and are methods on the response object. To set the charset, use e.g.:

In ASP.Net, setting Response.ContentEncoding will take care both of the charset parameter in the HTTP Content-Type as well as of the actual encoding of the document sent out (which of course have to be the same). The default can be set in the globalization element in Web.config (or Machine.config , which is originally set to UTF-8).

Further reading

  • Setting charset information in .htaccess
  • Checking HTTP Headers
  • Tutorial, Handling character encodings in HTML and CSS
  • Related links, Setting up a server
    • Characters
    • Setting the HTTP charset parameter
    • Characters
    • Characters

    Источник

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