HttpUtility
HttpUtility是一个轻量级的开源MIT许可项目,它有助于向服务器发送HTTP请求。它使用URLSession向API发送请求,并在成功的情况下返回包含解码对象的Result枚举,或者在失败的情况下返回错误。目前,这个工具仅解码由服务器返回的JSON响应。
用途目的
大多数情况下,iOS应用只是执行简单的HTTP操作,这包括向服务器发送请求并获取响应,并将结果显示给用户。如果您的iOS应用这样做,则可能使用此工具,该工具不会做太多重工作,只是将您的请求推送到服务器,并返回解码后的对象。
安装
CocoaPods
CocoaPods 是 Cocoa 项目的依赖管理器。关于使用和安装说明,请访问他们的网站。要使用 CocoaPods 将 HttpUtility 集成到您的 Xcode 项目中,请在 Podfile 中指定它。
pod 'HttpUtility', '~> 1.2'
使用 HttpUtility
简介
HttpUtility 可用于基本 HTTP 操作,如 GET、POST、PUT 和 DELETE。它使用 URLSession 执行操作,并且仅仅是它的包装。
此实用工具的最好之处在于,它接受一个简单的 URL,并在请求成功时返回解码的对象,在请求失败时返回错误。告别编写循环和自定义代码来解析 JSON 响应吧。
下述是一些示例,说明如何使用此实用工具
- GET 请求
- POST 请求
- 带有查询字符串参数的请求
- 带有 MultiPartFormData 的请求
- 带有身份验证令牌的请求
- 在实用工具中自定义 JSONDecoder
- HUNetworkError
GET 请求示例
let utility = HTTPUtility.shared // using the shared instance of the utility to make the API call
let requestUrl = URL(string: "http://demo0333988.mockable.io/Employees")
let request = HURequest(withUrl: requestUrl!, forHttpMethod: .get)
utility.request(huRequest: request, resultType: Employees.self) { (response) in
switch response
{
case .success(let employee):
// code to handle the response
case .failure(let error):
// your code here to handle error
}
}
POST 请求示例
httpUtility 具有一个名为 "requestBody" 的额外参数,您应在其中附加要发送到服务器的数据,例如在给定的示例中,RegisterUserRequest 是从 Encodable 协议 继承的结构体
let utiltiy = HttpUtility.shared // using the shared instance of the utility to make the API call
let requestUrl = URL(string: "https://api-dev-scus-demo.azurewebsites.net/api/User/RegisterUser")
let registerUserRequest = RegisterUserRequest(firstName: "code", lastName: "cat15", email: "[email protected]", password: "1234")
let registerUserBody = try! JSONEncoder().encode(registerUserRequest)
let request = HURequest(withUrl: requestUrl!, forHttpMethod: .post, requestBody: registerUserBody)
utility.request(huRequest: request, resultType: RegisterResponse.self) { (response) in
switch response
{
case .success(let registerResponse):
// code to handle the response
case .failure(let error):
// your code here to handle error
}
带查询字符串参数的 GET 请求
let utiltiy = HttpUtility.shared // using the shared instance of the utility to make the API call
let request = PhoneRequest(color: "Red", manufacturer: nil)
// using the extension to convert the encodable request structure to a query string url
let requestUrl = request.convertToQueryStringUrl(urlString:"https://api-dev-scus-demo.azurewebsites.net/api/Product/GetSmartPhone")
let request = HURequest(withUrl: requestUrl!, forHttpMethod: .get)
utility.request(huRequest: request, resultType: PhoneResponse.self) { (response) in
switch response
{
case .success(let phoneResponse):
// code to handle the response
case .failure(let error):
// your code here to handle error
}
}
使用多部分表单数据的POST请求
let utiltiy = HttpUtility.shared // using the shared instance of the utility to make the API call
let requestUrl = URL(string: "https://api-dev-scus-demo.azurewebsites.net/TestMultiPart")
// your request model struct should implement the encodable protocol
let requestModel = RequestModel(name: "Bruce", lastName: "Wayne")
let multiPartRequest = HUMultiPartRequest(url: requestUrl!, method: .post, request: requestModel)
utility.requestWithMultiPartFormData(multiPartRequest: multiPartRequest, responseType: TestMultiPartResponse.self) { (response) in
switch response
{
case .success(let serviceResponse):
// code to handle the response
case .failure(let error):
// code to handle failure
}
}
认证令牌
let utility = HttpUtility.shared
let token = "your_token"
utility.authenticationToken = token
如果您使用基础或载体令牌,确保在令牌之前加入基础或载体
示例:基础令牌
let basicToken = "basic your_token"
let utility = HttpUtility.shared
utility.authenticationToken = basicToken
示例:载体令牌
let bearerToken = "bearer your_token"
let utility = HttpUtility.shared
utility.authenticationToken = bearerToken
自定义JSONDecoder
有时候,您可能需要控制用于解码JSON的默认JSONDecoder的行为,在这样的情况下,HTTPUtility提供了一个默认的初始化方法,您可以在其中提供自己的自定义JSONDecoder,HTTPUtility将使用这个Decoder,下面是如何实现的
let customJsonDecoder = JSONDecoder()
customJsonDecoder.dateEncoding = .millisecondsSince1970
let utility = HttpUtility.shared
utility.customJsonDecoder = customJsonDecoder
令牌和自定义JSONDecoder
有时,在传递令牌而默认的JSONDecoder不足以满足需求时,您可以使用工具类的init方法来传递令牌和一个自定义的JSONDecoder,以便在发送API请求和解析JSON响应时同时使用。
let utility = HttpUtility.shared
let customJsonDecoder = JSONDecoder()
customJsonDecoder.dateEncoding = .millisecondsSince1970
let bearerToken = "bearer your_token"
utility.customJsonDecoder = customJsonDecoder
utility.authenticationToken = bearerToken
HUNetworkError
HUNetworkError结构提供了详细的描述,有助于调试,以下是在发生错误时将填充以下属性:
-
状态: 这将包含我们从服务器接收请求的HTTPStatus代码。
-
服务端响应: 这将是您从服务器接收的响应的JSON字符串。(不要与错误参数混淆)如果服务端返回错误JSON数据,则该消息将被解码为人类可读的字符串。
-
请求URL: 您刚才调用的请求URL。
-
请求体: 如果在POST请求中失败,则此属性将包含发送到服务器的HTTPBody的字符串表示形式。
-
原因: 此属性将包含从错误闭包参数中的调试描述。
这个工具用于执行基本任务,目前正在不断发展,但如果您有任何特定的功能想法,请随时提出来,我将尽最大努力实现它。