接受的答案非常实用,请确保看到它。但是有两个基本差异需要深入讨论:
HTTP请求中标题和参数的放置位置
URL与HTTP消息不同。 HTTP消息可以是请求或响应。在这个答案中,我将专注于请求。
HTTP请求主要由URL、HTTP方法、HTTP标题(其中包含其他块,但我只是提到我们最关心的部分)组成。
Request = Request-Line
*(( general-header
| request-header
| entity-header ) CRLF)
CRLF
[ message-body ]
请求行是:
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
CLRF
类似于换行符。
更多信息请参见此处和此处。您可能需要在链接之间来回翻阅,直到弄明白为止。如果您真的想深入了解,则可以查看此RFC。
所以基本上一个请求是这样的:
POST /cgi-bin/process.cgi?tag=networking&order=newest HTTP/1.1
User-Agent: Mozilla/4.0 (compatible
Host: www.tutorialspoint.com
Content-Type: text/xml
Content-Length: 60
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
first=Zara&last=Ali
查询参数(query params)位于URL内。HTTP头不是URL的一部分,它们是HTTP消息的一部分。在上面的示例中,query params是tag=networking&order=newest
,头文件如下:
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: text/xml; charset=utf-8
Content-Length: 60
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
当您发起网络请求时,使用http协议发送一个结构化的字符串。该字符串通过TCP连接发送。
2 - 为什么和在哪种情况下选择一种方法优于另一种方法
如果涉及到请求或客户端信息,则使用标头;但如果涉及请求本身的内容(例如从服务器请求的内容、用于识别返回项目的一些详细信息、要保存在Web服务器上的某些详细信息等),则使用参数。大多数情况下,应用程序的标头都是相同的,但由于基于内容,因此应更加丰富多样。使用
URLComponents
进行构建。
class UnsplashRequester {
static let session = URLSession.shared
static let host = "api.unsplash.com"
static let photosPath = "/photos"
static let accessKey = "My_access_key"
static func imageRequester(pageValue: String, completion: @escaping (Data?) -> Void) {
var components = URLComponents()
components.scheme = "https"
components.host = host
components.path = photosPath
components.queryItems = [URLQueryItem(name: "page", value: pageValue)]
let headers: [String: String] = ["Authorization": "Client-ID \(accessKey)"]
var request = URLRequest(url: components.url!)
for header in headers {
request.addValue(header.value, forHTTPHeaderField: header.key)
}
let task = session.dataTask(with: request) { data, _, error in
}
}
}