OkHttp3 Header 爲什麼不能傳中文?

簡單解釋

HTTP 協議只支持在 Header 中 傳輸 ISO-8859-1 編碼格式

Hypertext Transfer Protocol – HTTP/1.1

14.2 Accept-Charset The Accept-Charset request-header field can be used to indicate what character sets are acceptable for the response.
This field allows clients capable of understanding more comprehensive
or special- purpose character sets to signal that capability to a
server which is capable of representing documents in those character
sets.

  Accept-Charset = "Accept-Charset" ":"
          1#( ( charset | "*" )[ ";" "q" "=" qvalue ] ) Character set values are described in section 3.4. Each charset MAY be given an

associated quality value which represents the user’s preference for
that charset. The default value is q=1. An example is

  Accept-Charset: iso-8859-5, unicode-1-1;q=0.8 The special value "*", if present in the Accept-Charset field, matches every character

set (including ISO-8859-1) which is not mentioned elsewhere in the
Accept-Charset field. If no “*” is present in an Accept-Charset field,
then all character sets not explicitly mentioned get a quality value
of 0, except for ISO-8859-1, which gets a quality value of 1 if not
explicitly mentioned.

If no Accept-Charset header is present, the default is that any
character set is acceptable. If an Accept-Charset header is present,
and if the server cannot send a response which is acceptable according
to the Accept-Charset header, then the server SHOULD send an error
response with the 406 (not acceptable) status code, though the sending
of an unacceptable response is also allowed.

OkHttp 在添加時做了判斷

/**
     * Add a header with the specified name and value. Does validation of header names and values.
     */
    fun add(name: String, value: String) = apply {
      checkName(name)
      checkValue(value, name)
      addLenient(name, value)
    }

    private fun checkName(name: String) {
      require(name.isNotEmpty()) { "name is empty" }
      for (i in 0 until name.length) {
        val c = name[i]
        require(c in '\u0021'..'\u007e') {
          format("Unexpected char %#04x at %d in header name: %s", c.toInt(), i, name)
        }
      }
    }

    private fun checkValue(value: String, name: String) {
      for (i in 0 until value.length) {
        val c = value[i]
        require(c == '\t' || c in '\u0020'..'\u007e') {
          format("Unexpected char %#04x at %d in %s value: %s", c.toInt(), i, name, value)
        }
      }
    }

如果你強傳中文,也是可以的,但是,你會發現服務器端收到是亂碼!

Headers.Builder headerBuilder = new Headers.Builder();
headerBuilder.addUnsafeNonAscii(header.getKey(), header.getValue());

參考文章

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章