我正在测试 XMLParsing 库(使用带有 XML 请求的 Codable 协议)
XMLParsing 库链接: https ://github.com/ShawnMoore/XMLParsing
使用https://openweathermap.org API
API 链接是“ http://api.openweathermap.org/data/2.5/weather ”
我的模型是
struct weather:Codable {
let q : String
let appid : String
let mode : String
}
并且请求是
var request = URLRequest(url: URL(string: "http://api.openweathermap.org/data/2.5/weather")!)
request.httpMethod = "POST"
let post2 = weather(q: "london", appid: "f4be702b940e5073d765cb2473f0b31b", mode: "xml")
do{
let body = try XMLEncoder().encode(post2, withRootKey: "current")
request.httpBody = body
} catch{}
let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
if error != nil {
print("error: \(String(describing: error))")// Handle error…
return
}
guard let data = data else {return }
print("response: \(response)")
print("data: \(data)")
}
task.resume()
不知道问题出在哪里!我总是收到错误代码 401
response: Optional(<NSHTTPURLResponse: 0x600003bdedc0> { URL: http://api.openweathermap.org/data/2.5/weather } { Status Code: 401, Headers {
"Access-Control-Allow-Credentials" = (
true
);
"Access-Control-Allow-Methods" = (
"GET, POST"
);
"Access-Control-Allow-Origin" = (
"*"
);
Connection = (
"keep-alive"
);
"Content-Length" = (
107
);
"Content-Type" = (
"application/json; charset=utf-8"
);
Date = (
"Mon, 14 Jan 2019 07:14:16 GMT"
);
Server = (
openresty
);
"X-Cache-Key" = (
"/data/2.5/weather?"
);
} })
data: 107 bytes
但在 PostMan 上它工作正常并获取当前数据