有没有其他方法可以使用自定义标头和正文在不使用第三方库的情况下发送HTTP“ POST”请求?

时间:2019-01-22 14:40:14

标签: ios http post networking request

我正在尝试发送对Web服务的HTTP“ POST”请求,该请求应返回base64编码的图片。这是对该服务的HTTP请求示例:

https://imgur.com/a/XTbVxEW

我正在尝试以下操作:

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

我收到错误401未经授权,我实际上不知道这是因为我的请求很糟糕还是仅仅是登录名首字母。如果有人可以检查代码并告诉我它是否确实与上面显示的请求示例相对应,那就太好了。

谢谢!

2 个答案:

答案 0 :(得分:1)

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

request.httpMethod = “POST”

答案 1 :(得分:0)

事实证明,我错误地使用了CommonCrypto哈希函数,但最终使用了它:

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

它返回的SHA256哈希值是我需要的正确值,也许这将来可能会对某人有所帮助。