JSONRequest 是一个小巧的 Swift 库,用于执行 HTTP JSON 请求。
JSONRequest 提供了一个简洁且易于使用的 API,用于异步和同步地提交 HTTP 请求(参见为什么同步?你疯了吗?)。
let result = JSONRequest.get("http://httpbin.org/get?hello=world")
if let value = result.data?["args"]??["hello"] as? String {
print(value) // Outputs "world"
}
let postResult = JSONRequest.post("http://httpbin.org/post", payload: ["hello": "world"])
if let value = postResult.data?["json"]??["hello"] as? String {
print(value) // Outputs "world"
}
JSONRequest.get("http://httpbin.org/get?hello=world") { result in
if let value = result.data?["args"]??["hello"] as? String {
print(value) // Outputs "world"
}
}
JSONRequest.post("http://httpbin.org/post", payload: ["hello": "world"]) { result in
if let value = result.data?["json"]??["hello"] as? String {
print(value) // Outputs "world"
}
}
URL 参数可以作为 [String: AnyObject]
字典传递,并会自动进行 URL 编码并附加到 URL 字符串上。所有请求都允许查询参数,无论使用的 HTTP 方法是什么。查询参数字典的值在 URL 编码之前将转换为 String
。
响应会自动解析(预期为有效的 JSON 响应),并以 AnyObject 格式返回(有效的 JSON 值包括 Array
、Dictionary
、Int
、Double
、String
和 nil
)
所有 JSONRequest 请求都会自动包含以下默认头:
Content-Type: application/json
Accept: application/json
可以通过 urlRequest
属性访问底层的 NSMutableURLRequest
对象。