Swift: 无法将 .prettyPrinted 格式字符串添加到 forHTTPHeaderField

Swift: Unable to add .prettyPrinted format String to forHTTPHeaderField

继续from this question

我正在尝试将 [String : Any] 转换为 String,然后将 String 传递给 forHTTPHeaderField

尝试 1: 没有 Pretty

let encoder = JSONEncoder()

if let json = try? encoder.encode(jsonDict) {
   convertedString = String(data: json, encoding: .utf8)!
}

print("JsonStringFormat     ", convertedString )

let url = NSURL(string: getMenuURL)
let request = NSMutableURLRequest(url: url! as URL)
request.setValue(convertedString, forHTTPHeaderField: "SessionInfo")

print("\nHEADer__reQQ__    ", request.allHTTPHeaderFields)

输出:

JsonStringFormat      {"Token":"96FFC5B994514B3D","UICulture":"en-CA ","LanguageCode":"ENG","CompanyID":"QAP","IMEINo":"1jzBG3TSrMzj\/tKihlEv8g=="}
HEADer__reQQ__     ["SessionInfo": "{\"Token\":\"96FFC5B994514B3D\",\"LanguageCode\":\"ENG\",\"UICulture\":\"en-CA \",\"CompanyID\":\"QAP\",\"IMEINo\":\"1jzBG3TSrMzj\/tKihlEv8g==\"}"]

尝试 2: 打印 .pretty

let encoder = JSONEncoder()

// ADDING PRETTY FORMAT
encoder.outputFormatting = .prettyPrinted

if let json = try? encoder.encode(jsonDict) {
   convertedString = String(data: json, encoding: .utf8)!
}

print("PrettyJsonStringFormat     ", convertedString )

let url = NSURL(string: getMenuURL)
let request = NSMutableURLRequest(url: url! as URL)
request.setValue(convertedString, forHTTPHeaderField: "SessionInfo")

print("\nPrettyHeader__    ", request.allHTTPHeaderFields)

输出:

PrettyJsonStringFormat      {
  "Token" : "70E277954143414A",
  "UICulture" : "en-CA ",
  "LanguageCode" : "ENG",
  "CompanyID" : "QAP",
  "IMEINo" : "1jzBG3TSrMzj\/tKihlEv8g=="
}

PrettyHeader__    [:]

如果我选择尝试 1,BackSlash \ 将追加该值。为了避免这种情况,我选择了尝试 2 [Pretty Printed]

我不知道为什么 request.allHTTPHeaderFields 没有添加 header 值。

请指导我。

那是因为 Attempt2 中的 convertedString 有多行。

RFC 表示 header 多行字段值已弃用。

Historically, HTTP header field values could be extended over multiple lines by preceding each extra line with at least one space or horizontal tab (obs-fold). This specification deprecates such line folding except within the message/http media type (Section 8.3.1). A sender MUST NOT generate a message that includes line folding (i.e., that has any field-value that contains a match to the obs-fold rule) unless the message is intended for packaging within the message/http media type.

而且,setValue(_:forHTTPHeaderField:) 似乎忽略了这些值。

// This does nothing. Just ignoring the value "A\nB"
request.setValue("A\nB", forHTTPHeaderField: "C")

此外,Attempt1中的反斜线也没有问题。收到请求的服务器将正确处理该值。

你应该在这个 link

中检查这个答案

您对标准的理解是正确的。过去,RFC 2616 支持 multi-line header 值。此功能被称为 "Line Folding":

HTTP/1.1 header field values can be folded onto multiple lines if the continuation line begins with space or horizontal tab. All linear white space, including folding, has the same semantics as SP. A recipient MAY replace any linear white space with a single SP before interpreting the field value or forwarding the message downstream.