- Xml. Encoding Class
- Definition
- Remarks
- Properties
- Methods
- Explicit Interface Implementations
- Extension Methods
- Кодировка в XML документе
- Символьная кодировка
- Юникод
- UTF-8 — Веб-стандарт
- Кодировка XML документа
- Ошибки XML
- Заключение
- Злой XML с двумя кодировками
- Какие кодировки работают в XML
- Как парсеры определяют кодировку
- problem with utf-8 charset in filename #82
- Comments
- asafbennatan commented Jan 19, 2016
- alexbbb commented Jan 19, 2016
- problem with utf-8 charset in filename #82
- Comments
- asafbennatan commented Jan 19, 2016
- alexbbb commented Jan 19, 2016
Xml. Encoding Class
Definition
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Supported character encodings.
Remarks
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Properties
Returns the runtime class of this Object .
(Inherited from Object)
Returns the Class object corresponding to this enum constant’s enum type.
(Inherited from Enum)
The handle to the underlying Android instance.
(Inherited from Object)
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
(Inherited from Enum)
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
(Inherited from Enum)
Methods
(Inherited from Enum)
Compares this enum with the specified object for order.
(Inherited from Enum)
Returns true if the specified object is equal to this enum constant.
(Inherited from Enum)
Returns a hash code for this enum constant.
(Inherited from Enum)
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
(Inherited from Object)
Returns the name of this enum constant, exactly as declared in its enum declaration.
(Inherited from Enum)
Wakes up a single thread that is waiting on this object’s monitor.
(Inherited from Object)
Wakes up all threads that are waiting on this object’s monitor.
(Inherited from Object)
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
(Inherited from Enum)
Sets the Handle property.
(Inherited from Object)
Returns a string representation of the object.
(Inherited from Object)
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.
(Inherited from Object)
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.
(Inherited from Object)
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.
(Inherited from Object)
Explicit Interface Implementations
IJavaPeerable.Disposed() | (Inherited from Object) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Object) |
IJavaPeerable.Finalized() | (Inherited from Object) |
IJavaPeerable.JniManagedPeerState | (Inherited from Object) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Object) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Object) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Object) |
Extension Methods
Performs an Android runtime-checked type conversion.
Источник
Кодировка в XML документе
XML документы могут содержать символы в различных международных кодировках.
Чтобы не возникало ошибок, необходимо указывать, какая кодировка используется в XML документе, либо сохранять файл в универсальной кодировке UTF-8.
Символьная кодировка
Символьная кодировка определяет уникальный бинарный код для различных символов, используемых в документе.
В компьютерных терминах символьную кодировку также называют символьным набором, символьной раскладкой, кодовым набором и кодом страницы.
Юникод
Юникод — это промышленный стандарт для символьной кодировки текстового документа. Он определяет (почти) все возможные международные символы по именам и числам.
Юникод имеет две разновидности: UTF-8 и UTF-16.
UTF = формат преобразования Юникода (анг. Unicode Transformation Format).
UTF-8 использует один байт (8 бит) для представления общепринятых символов и два (или три) байта для всех остальных символов.
UTF-16 использует два байта (16 бит) для большинства символов и три байта для всего остального.
UTF-8 — Веб-стандарт
UTF-8 — стандартная кодировка символов в сети Интернет.
UTF-8 считается кодировкой по умолчанию в HTML-5, CSS, JavaScript, PHP, SQL и XML.
Кодировка XML документа
Первая строка в XML документе называется прологом:
Пролог является необязательным и, как правило, содержит номер версии XML.
Кроме этого, он может содержать информацию о кодировке XML документа. Следующий пролог определяет кодировку UTF-8:
Стандартизация XML устанавливает, что все приложения XML должны понимать кодировки UTF-8 и UTF-16.
UTF-8 является кодировкой по умолчанию для XML документов без информации о кодировке.
Кроме этого, большинство систем приложений XML работают с такими кодировками, как ISO-8859-1, Windows-1252 и ASCII.
Ошибки XML
Очень часто XML документы создаются на одном компьютере, на сервер выгружается с другого, а в браузере отображаются на третьем компьютере.
Если кодировка некорректно интерпретируется всеми тремя компьютерами, то браузер отобразит бессмысленный набор символов, либо вообще выдаст сообщение об ошибке.
Наилучшим выбором в этом случае будет использование кодировки UTF-8. UTF-8 позволяет отображать практически все международные символы, и, кроме этого, она считается кодировкой по умолчанию, если не указана другая кодировка.
Заключение
Когда вы пишите XML документ:
- Используйте текстовый редактор, который позволяет изменять кодировку документа
- Убедитесь, что редактор настроен на использование нужной кодировки
- Опишите используемую кодировку в соответствующей декларации
- UTF-8 является самой безопасной кодировкой
- UTF-8 является стандартом в сети Интернет
Источник
Злой XML с двумя кодировками
WAFы видят вместо документа белый шум!
00000000 | 3C3F 786D 6C20 7665 7273 696F 6E3D 2231 | . .1.3.3.7. |
В статье — небольшой рассказ про кодировки в XML и про обход WAFов с их помощью.
Какие кодировки работают в XML
Спецификация обязывает парсеры понимать две кодировки: UTF-8 и UTF-16. Парсеры поддерживают больше, но для атаки хватит и этих.
UTF-8 и UTF-16 отображают одни и те же символы — из таблицы Юникода.
Разница между кодировками в том, как они хранят номер символа.
UTF-8
Один символ — от одного до четырех байт.
Код символа хранится по шаблону:
Количество байт | Значащих бит | Бинарный код |
1 | 7 | 0xxxxxxx |
2 | 11 | 110xxxxx 10xxxxxx |
3 | 16 | 1110xxxx 10xxxxxx 10xxxxxx |
4 | 21 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Кодировать символы избыточно нельзя. Самый короткий способ — верный.
UTF-16
Один символ — два или четыре байта.
Код символа хранится по шаблону:
Количество байт | Значащих бит | Бинарный код |
2 | 16 | xxxxxxxx xxxxxxxx |
4 * | 20 | 110110xx xxxxxxxx 110111xx xxxxxxxx |
* Из кода предварительно вычитается 0x010000
Запись символа с помощью 4-х байт называется суррогатной парой. Пара состоит из двух обычных символов, но из зарезервированного диапазона: от U+D800 до U+DFFF. Половинки пары сами по себе недействительны.
UTF-16 бывает двух видов: UTF-16BE и UTF-16LE (big-endian / little-endian). В них разный порядок байт.
Big-endian — «естественный» порядок байт, как у арабских цифр.
Little-endian — обратный порядок байт.
Примеры записи символов в UTF-16BE и UTF-16LE
Кодировка | Символ | Бинарный код |
UTF-16BE | U+003F | 00000000 00111111 |
UTF-16LE | U+003F | 00111111 00000000 |
UTF-16BE * | U+1D6E5 | 11011000 00110101 11011110 1100101 |
UTF-16LE * | U+1D6E5 | 00110101 11011000 11100101 11011110 |
* В четырех-байтовых символах группы из 2-х байт переворачиваются отдельно. Это сделано для обратной совместимости с Unicode 1.0, где все символы состояли только из двух байт.
Как парсеры определяют кодировку
Парсеры определяют кодировку четырьмя способами:
Внешняя информация о кодировке
В некоторых сетевых протоколах есть специальное поле для кодировки:
Передача кодировки в протоколе WebDav
Чаще всего это протоколы, которые построены по стандарту MIME: например SMTP, HTTP и WebDAV.
Byte Order Mark (BOM)
BOM — символ с кодом U+FEFF.
Если парсер найдет его в начале, то он определит кодировку по тому, как он записан.
Источник
problem with utf-8 charset in filename #82
Comments
asafbennatan commented Jan 19, 2016
hi ,
i am using android-upload-service to upload a file with filename written in hebrew (utf-8 encoding),
on the other end i’m getting . instead of the filename,
is there any way to set the charset ?
(i have currently tried setting the content-type to :multipart/form-data; charset=utf-8 but this breaks the upload entirely as the server returns error)
Thanks.
The text was updated successfully, but these errors were encountered:
alexbbb commented Jan 19, 2016
Hi,
the behaviour you described is perfectly normal. I’m going to explain you why.
First, setting the content type as you’ve done is wrong and it’s normal that your server side complains about it. The content type specifies the MIME type of the file and has nothing to do with the filename.
Android Upload Service is compliant to RFC2388. In section 4.4 is stated that:
The original local file name may be supplied as well, either as a
«filename» parameter either of the «content-disposition: form-data»
header or, in the case of multiple files, in a «content-disposition:
file» header of the subpart. The sending application MAY supply a
file name; if the file name of the sender’s operating system is not
in US-ASCII, the file name might be approximated, or encoded using
the method of RFC 2231.
In the current release 1.6 and in the upcoming 2.0, the filename is encoded in US-ASCII (as you can see here) and RFC 2231 is not supported. I suggest you to use ASCII file names though, to have the maximum compatibility across all the platforms and servers.
I’ve worked on projects where upload of cyrillic filenames were involved and I’ve always used ASCII file names. If you need to know the original file name, as a quick fix you can simply pass it as a request parameter, which is encoded in UTF-8 and then use it on your server side.
Источник
problem with utf-8 charset in filename #82
Comments
asafbennatan commented Jan 19, 2016
hi ,
i am using android-upload-service to upload a file with filename written in hebrew (utf-8 encoding),
on the other end i’m getting . instead of the filename,
is there any way to set the charset ?
(i have currently tried setting the content-type to :multipart/form-data; charset=utf-8 but this breaks the upload entirely as the server returns error)
Thanks.
The text was updated successfully, but these errors were encountered:
alexbbb commented Jan 19, 2016
Hi,
the behaviour you described is perfectly normal. I’m going to explain you why.
First, setting the content type as you’ve done is wrong and it’s normal that your server side complains about it. The content type specifies the MIME type of the file and has nothing to do with the filename.
Android Upload Service is compliant to RFC2388. In section 4.4 is stated that:
The original local file name may be supplied as well, either as a
«filename» parameter either of the «content-disposition: form-data»
header or, in the case of multiple files, in a «content-disposition:
file» header of the subpart. The sending application MAY supply a
file name; if the file name of the sender’s operating system is not
in US-ASCII, the file name might be approximated, or encoded using
the method of RFC 2231.
In the current release 1.6 and in the upcoming 2.0, the filename is encoded in US-ASCII (as you can see here) and RFC 2231 is not supported. I suggest you to use ASCII file names though, to have the maximum compatibility across all the platforms and servers.
I’ve worked on projects where upload of cyrillic filenames were involved and I’ve always used ASCII file names. If you need to know the original file name, as a quick fix you can simply pass it as a request parameter, which is encoded in UTF-8 and then use it on your server side.
Источник