首页 > 解决方案 > 在不使用第三方库的情况下使用自定义标头和正文发送 HTTP“POST”请求是否有不同的方法?

问题描述

我正在尝试为应该返回 base64 编码图片的 Web 服务发送 HTTP“POST”请求。这是服务的 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 Unauthorized,我实际上不知道是因为我的请求全部错误还是只是登录名缩写。如果有人可以检查代码并告诉我它是否真的对应于上面显示的请求示例,那就太好了。

谢谢!

标签: ioshttppostnetworkingrequest

解决方案


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

request.httpMethod = “POST”

推荐阅读