简体   繁体   中英

Is there a different way how to send a HTTP “POST” request without using third party libraries using custom header and body?

I am trying to send a HTTP "POST" request for a web-service that should return a base64 encoded picture. This is an example HTTP request for the service:

https://imgur.com/a/XTbVxEW

I am trying the following:

func fetchPicture(username: String, password: String) {
    let url = URL(string: "https://myurl.com/download/bootcamp/image.php")!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    request.setValue(password.stringToSHA1Hash(), forHTTPHeaderField: "Authorization")
    let postString = "username=\(username)"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }
        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
    }
    task.resume()
}

I am getting an error 401 Unauthorized, I don't actually know whether it is because my request is bad all together or just the login initials. It would be grand if someone could go over the code and tell me if it actually corresponds to the request example shown above.

Thanks!

我注意到的第一件事是您没有设置请求HTTP方法:

request.httpMethod = “POST”

As it turns out, I was using the CommonCrypto hashing function wrongly, I ended up using this instead:

https://github.com/apple/swift-package-manager/blob/master/Sources/Basic/SHA256.swift

And the SHA256 hash it returned was the correct one I needed, maybe this might help someone in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM