POST URLRequest doesn't work in Swift 4

旧时模样 提交于 2020-01-24 01:36:06

问题


I want to use HTTP request to post an image on Imgur. I used Postman first to make sure my API logic is correct.

Here is my setting for Postman (myid is client id):

This request succeeded, but the request failed in Swift with URLRequest and URLSession (Status Code: 400).

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)")
    }
}

I tried to encode the body data using JSON, but it didn't work.

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

来源:https://stackoverflow.com/questions/48715002/post-urlrequest-doesnt-work-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!