使用XMLParsing swift库进行POST请求时遇到错误代码401

我正在测试使用Codable协议的XMLParsing库

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))")// 处理错误信息
                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

点赞
用户6040542
用户6040542

我把它作为链接的参数并将请求更改为 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()

    }

}
2019-01-14 08:46:00