gpt4 book ai didi

swift - 使用 XMLParsing swift 库发布请求时出现错误 401

转载 作者:行者123 更新时间:2023-11-30 10:53:51 26 4
gpt4 key购买 nike

我正在测试 XMLParsing 库(使用 Codable 协议(protocol)和 XML 请求)

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 上它工作正常并获取当前数据

enter image description here

最佳答案

感谢@OOPer

我将其作为参数放在链接上,并将请求更改为 GET现在工作正常

import UIKit
import XMLParsing


struct current:Codable {
let city : City?
}

struct City:Codable {
let id : String?

}

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()




let request = URLRequest(url: URL(string: "http://api.openweathermap.org/data/2.5/weather?q=london&appid=f4be702b940e5073d765cb2473f0b31b&mode=xml")!)

let session = URLSession.shared

let task = session.dataTask(with: request) { (data, response, error) in



do{

guard (error == nil) else {
print("There is error")
return
}

guard let data = data else {return}

let newData = try XMLDecoder().decode(current.self, from: data)

print((newData.city?.id)!)

}catch let error {
print("there is error",error)
}

}
task.resume()


}


}

关于swift - 使用 XMLParsing swift 库发布请求时出现错误 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54177119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com