POST URLRequest在Swift 4中不起作用

时间:2018-02-09 22:24:50

标签: swift nsurlsession nsurlrequest imgur urlrequest

我想使用HTTP请求在Imgur上发布图片。我首先使用Postman来确保我的API逻辑是正确的。

以下是我对Postman的设置(myid是客户端ID):

enter image description here enter image description here

此请求成功,但使用URLRequest和URLSession(状态代码:400)在Swift中请求失败。

var request = URLRequest(url: self.uploadURL!)
request.httpMethod = "POST"
request.setValue("Client-ID " + myid,
                    forHTTPHeaderField: "Authorization")
let data = "image=\(base64String)&type=base64".data(using: .utf8, 
                    allowLossyConversion: false)
request.httpBody = data

// Upload task
let task = URLSession.shared.dataTask(with: request) {
    data, response, error in
    print("Responeded!!")
    if let error = error {
        print ("error: \(error)")
        return
    }
    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           
        print("statusCode should be 200, but is \(httpStatus.statusCode)")
        print("response = \(response)")
    }
}

我尝试使用JSON对身体数据进行编码,但它没有用。

let parameters = ["image" : base64String, "type" : "base64"]
let data = JSONSerialization.data(withJSONObject: parameters,
                    options: .init(rawValue: 0))
request.httpBody = data

0 个答案:

没有答案