[英]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. 我正在尝试发送对Web服务的HTTP“ POST”请求,该请求应返回base64编码的图片。 This is an example HTTP request for the service:
这是对该服务的HTTP请求示例:
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. 我收到错误401未经授权,我实际上不知道这是因为我的请求很糟糕还是只是登录名首字母。 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: 事实证明,我错误地使用了CommonCrypto哈希函数,最终我使用了它:
https://github.com/apple/swift-package-manager/blob/master/Sources/Basic/SHA256.swift 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. 它返回的SHA256哈希值是我需要的正确值,也许将来可能会对某人有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.