0

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):

enter image description here enter image description here

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
Jay Wang
  • 2,650
  • 4
  • 25
  • 51
  • This indicates that, although the server received the request, it was malformed in some way: "[400 BAD REQUEST](https://httpstatuses.com/400): The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing)." –  Feb 09 '18 at 22:36
  • @ColGraff Yeah, but I am not sure where I did wrong. I just implemented following the Postman parameters. – Jay Wang Feb 09 '18 at 22:37
  • The format for the post request is: [here](https://apidocs.imgur.com/#4b8da0b3-3e73-13f0-d60b-2ff715e8394f). You don't show how you base64 encode the image, or if the image is equal or less than 10MB in size. Can you show how you encode the image? –  Feb 09 '18 at 22:48
  • @ColGraff For this test, I used an online base64 encoder to encode my image. Postman successfully posted the base64, but URLRequest failed with the exactly same string. – Jay Wang Feb 09 '18 at 22:50
  • Try encoding an image yourself with [the code in this question](https://stackoverflow.com/questions/11251340/convert-between-uiimage-and-base64-string) and see if it works. –  Feb 09 '18 at 22:56
  • @ColGraff I did converted NSImage to base64 in my code, and I tested the base64 result in HTML file. The URLRequest fails so I changed to use an online base64 encoder result to both Swift and Postman. – Jay Wang Feb 09 '18 at 23:10
  • 1
    Your Postman image shows `form-data`, which means your `Content-Type` is `multipart/form-data`. But your code is sending the content with normal POST request, `Content-Type: x-www-form-urlencoded`. Some servers cannot work with both content-type. Find "how to send multipart/form-data in Swift". – OOPer Feb 09 '18 at 23:56
  • @OOPer Oh i see. I just used Postman to generate swift code for `multipart/form-data` mode, and it works perfectly! One complain is the URLRequest under `multipart/form-data` mode is very messy lol. Thank you so much! – Jay Wang Feb 10 '18 at 02:14
  • Hey @JayWong where is your blog post for the app you made? I once saw it but cannot find it anymore. Im stuck with the error 400 invalid URL. – Potion Apr 02 '19 at 15:52
  • @Potion Hi! Wow where did you find my blog post? I am so glad that someone has seen it! Here is my [post](https://link.medium.com/VGabXcl3yV). – Jay Wang Apr 02 '19 at 17:29

0 Answers0