ios - 在不使用第三方库的情况下使用自定义标头和正文发送 HTTP“POST”请求是否有不同的方法?
问题描述
我正在尝试为应该返回 base64 编码图片的 Web 服务发送 HTTP“POST”请求。这是服务的 HTTP 请求示例:
我正在尝试以下操作:
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,我实际上不知道是因为我的请求全部错误还是只是登录名缩写。如果有人可以检查代码并告诉我它是否真的对应于上面显示的请求示例,那就太好了。
谢谢!
解决方案
我注意到的第一件事是您没有设置请求 HTTP 方法:
request.httpMethod = “POST”
推荐阅读
- javascript - PHP 中的 NumberFormatter 与 JS 中的 NumberFormat
- excel - 分发用户无法查看其代码的 Excel 加载项 (.xlam)
- javascript - 网站在 Galaxy S5 浏览器上无响应
- python - 我如何在 python 中实现 K 最近邻,它可以从头开始获得更好的准确性
- c - 列表中的学生 ID 没有被打印出来
- c# - 如何使用 ExcelDNA 访问 Excel 图表对象
- swift - 无法从 Firestore DocumentSnapshot 中提取日期或时间戳
- c++ - 制作一个使用模板创建类或子类对象的函数
- json - JsonSerializer 结构与 asp-net 核心 3.0
- r - 更改R中变量名称的函数