向api-rest发出请求的正确方法是什么?
let myUrl = URL(string: "https://myhost.com/test/wp-json/jwt-auth/v1/token")
var request = URLRequest(url:myUrl!)
o
let request = NSMutableURLRequest(url: NSURL(string: "https://myhost.com/test/wp-json/jwt-auth/v1/token")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
何时应该使用其中一个?
答案 0 :(得分:1)
除了Leo的评论外, 请在下面找到用于“请求和响应”的示例类,该类用于进行其余的api调用。
请求类:
public struct APIRequest {
let url: URL
let method: HTTPMethod
var httpHeaders: HTTPHeaders
let body: Data?
init(url: URL,
method: HTTPMethod,
httpHeaders: HTTPHeaders,
body: Data? = nil
) {
self.url = url
self.method = method
self.httpHeaders = httpHeaders
self.body = body
}
}
extension APIRequest {
public func asURLRequest() -> URLRequest {
var urlRequest = URLRequest(url: self.url)
for (headerField, headerValue) in self.httpHeaders {
urlRequest.addValue(headerValue, forHTTPHeaderField: headerField.rawValue)
}
urlRequest.httpMethod = self.method.rawValue
urlRequest.httpBody = self.body
return urlRequest
}
}
extension URLRequest {
public var debugDescription: String {
let urlString = "URL: \(self.url?.absoluteString ?? "")"
let methodString = "Method: \(self.httpMethod ?? "")"
var httpHeadersString = "Headers: \n"
for (headerField, headerValue) in self.allHTTPHeaderFields ?? [:] {
httpHeadersString = httpHeadersString.appending("\(headerField) : \(headerValue) \n")
}
// Print Body as JSON
let description = [
urlString,
methodString,
httpHeadersString
]
return "Request: { " + description.joined(separator: "\n") + " }"
}
}
响应类别
public struct APIResponse {
let request: URLRequest?
let response: HTTPURLResponse?
var jsonData: JSONObject?
var data: Data?
var statusCode: Int
var url: URL?
var httpHeaders: [AnyHashable: Any]?
var error: Error?
init(request: URLRequest?,
response: HTTPURLResponse?,
responseData: Data?,
error: Error?) {
self.request = request
self.response = response
self.jsonData = nil
self.data = nil
self.statusCode = 0
self.url = nil
self.httpHeaders = nil
if let httpResponse = response {
statusCode = httpResponse.statusCode
url = httpResponse.url
httpHeaders = httpResponse.allHeaderFields
data = responseData
}
if statusCode == 401 {
self.error = // Auth Error
} else if (200..<300).contains(statusCode) == false {
self.error = // Bad Error
}
}
}
HttpMethod
public enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
HttpHeaders
public typealias HTTPHeaders = [HttpHeadersKey: String]
public enum HttpHeadersKey: String {
case contentType = "Content-Type"
case userAgent = "User-Agent"
case accept = "Accept"
case date = "Date"
case authorization = "Authorization"
}
public enum MIMEType: String {
case json = "application/json"
case imagePng = "image/png"
}
public struct DefaultHeader {
var value = HTTPHeaders()
init() {
self.value[HttpHeadersKey.contentType] = MIMEType.json.rawValue
self.value[HttpHeadersKey.accept] = MIMEType.json.rawValue
self.value[HttpHeadersKey.date] = Date().rfc1123String()
}
}