问题
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