Alamofire 数据请求 & 数据解析 (上)

这是我参与更文挑战的第16天,活动详情查看: 更文挑战

Alamofire: Elegant Networking in Swift

Alamofire 介绍

Alamofire 是一个使用swift编写的的网络请求库,开发团队你肯定很熟悉,就是原AFNetworking团队;

功能非常的强大,下面是官方特性描述(英文更能表达原意思)

  • Chainable Request / Response Methods // 链式请求和响应方法调用,非常的易用

  • Combine Support // Combine 支持

  • URL / JSON Parameter Encoding // URL / JSON 参数编码

  • Upload File / Data / Stream / MultipartFormData 支持文件上传,数据 ,流,多表单数据上传

  • Download File using Request or Resume Data 下载资源支持断点续传

  • Authentication with URLCredential 验证

  • HTTP Response Validation 响应验证

  • Upload and Download Progress Closures with Progress 闭包返回上传下载进度

  • cURL Command Output 可以转化成curl命令

  • Dynamically Adapt and Retry Requests 对于请求拥有重试机制

  • TLS Certificate and Public Key Pinning

  • Network Reachability 网络状态监测

  • Comprehensive Unit and Integration Test Coverage 单元测试和性能测试

  • Complete Documentation 完善的文档

项目集成使用

//CocoaPods
pod 'Alamofire', '~> 5.4'

//Carthage
github "Alamofire/Alamofire" ~> 5.4

//Swift Package Manager
dependencies: [
    .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.4.0"))
]
复制代码

发起请求

简单请求

AF.request("https://httpbin.org/get").response { response in
    debugPrint(response)
}
复制代码

GET / POST / PUT / DELETE /DOWNLOAD

 switch identifier {
        case "GET":
            let login = Login(email: "aaa", password: "bbb")
            return AF.request("https://httpbin.org/get",parameters: login)
        case "POST":
            return AF.request("https://httpbin.org/post", method: .post)
        case "DELETE":
            return AF.request("https://httpbin.org/delete", method: .delete)
        case "PUT":
            return AF.request("https://httpbin.org/put", method: .put)
        case "DOWNLOAD":
            let destination = DownloadRequest.suggestedDownloadDestination(for: .cachesDirectory, in: .userDomainMask)
            return AF.download("https://httpbin.org/stream/1", to: destination)
        default:
            return nil
 }
复制代码

请求参数

URL / JSON Parameter Encoding

GET

 let login = Login(email: "aaa", password: "bbb")
 AF.request("https://httpbin.org/get",parameters: login) //参数会默认话成urlencoded "url": "https://httpbin.org/get?email=aaa&password=bbb"
复制代码

不知道你发现了,GET请求这里直接使用的Login 对象;只要参数遵循Encodable协议,那么最终ParameterEncoder都会把Parameter encode成需要的数据类型

POST

parameters 支持传递 login 对象,前提是login 是实现了Codeable的; 通过Charles抓包发现,POST的默认数据提交格式是: application/x-www-form-urlencoded 格式;

encoder: URLEncodedFormParameterEncoder.default

 let login = Login(email: "aaa", password: "bbb")
 AF.request("https://httpbin.org/post", method: .post, parameters: login)
复制代码

抓包

:method: POST
:scheme: https
:path: /post
:authority: httpbin.org
accept: */*
content-type: application/x-www-form-urlencoded; charset=utf-8
accept-encoding: br;q=1.0, gzip;q=0.9, deflate;q=0.8
user-agent: AlamofireDemo/1.0 (com.jzyd.AlamofireDemo.AlamofireDemo; build:1; iOS 14.5.0) Alamofire/5.4.1
accept-language: en;q=1.0
content-length: 22

email=aaa&password=bbb
复制代码

指定 content-type = application/json

encoder: JSONParameterEncoder.default)

struct Login: Encodable {
    let email:String
    let password:String
}

let login = Login(email: "aaa", password: "bbb")
AF.request("https://httpbin.org/post",
               method: .post,
               parameters: login,
               encoder: JSONParameterEncoder.default)
    .response { response in
        debugPrint(response)
}
复制代码

抓包

:method: POST
:scheme: https
:path: /post
:authority: httpbin.org
accept: */*
content-type: application/json
accept-encoding: br;q=1.0, gzip;q=0.9, deflate;q=0.8
user-agent: AlamofireDemo/1.0 (com.jzyd.AlamofireDemo.AlamofireDemo; build:1; iOS 14.5.0) Alamofire/5.4.1
accept-language: en;q=1.0
content-length: 32

{"email":"aaa","password":"bbb"}
复制代码

DOWNLOAD

let destination = DownloadRequest.suggestedDownloadDestination(for: .cachesDirectory, in: .userDomainMask)
AF.download("https://httpbin.org/stream/1", to: destination)
复制代码

HTTP Headers 请求头设置

提供3种初始化方式

/// 1. 无参构造
public init() {}

/// 通过以下方式添加值
func add(name: String, value: String)
func add(_ header: HTTPHeader)
复制代码
/// 2. 通过 HTTPHeader 数组构造
public init(_ headers: [HTTPHeader])

let headers: HTTPHeaders = [
    HTTPHeader(name: "Authorization", value: "Basic VXNlcm5hbWU6UGFzc3dvcmQ="),
    HTTPHeader(name: "Accept", value: "application/json")
]

AF.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)
}
复制代码
/// 3. 通过key/value 构造
public init(_ dictionary: [String: String])

let headers: HTTPHeaders = [
    "Authorization": "Basic VXNlcm5hbWU6UGFzc3dvcmQ=",
    "Accept": "application/json"
]

AF.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)
}
复制代码

数据解析

3种数据解析,明天继续分享

AlamofireDemo

演示了数据请求+ 3种数据解析+ Comic漫画网站数据展示

Snipaste_2021-06-17_23-51-51.png

参考

www.jianshu.com/p/b7174ed30…

www.jianshu.com/p/e159b32e7…

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享