我是编程新手,现在我正在学习使用 PHP 作为后端服务器构建一个 iOS 应用程序。
据我所知,在http方法中,如果我使用GET方法,就等于在浏览器中写了一个查询。
假设我想发送“id”作为查询项以从服务器获取 JSON 响应,我可以在浏览器中这样写
http:/website.com/post.php?id=23
我使用 PHP 构建我的后端,并捕获该 ID,我在服务器端代码中使用 $_REQUEST(据我所知,$_REQUEST 可以接受 GET 和 POST 方法)。
当我使用浏览器访问该路径时,我可以从服务器获取 JSON 数据响应。
但是,当我尝试使用 GET 方法从我的 iOS 应用程序发送该查询时,出现错误
错误:错误域=NSCocoaErrorDomain 代码=3840“无值”。UserInfo={NSDebugDescription=无值。}
但是当我将该 http 方法更改为 POST 时,它可以无缝地工作。这是当我想在我的 iOS 应用程序中发送请求时激活的方法。我只想获取数据,而不是在数据库中创建新数据。
func loadPost() {
let id = userInfo!["id"] as! String
let url = URL(string: "http://localhost/Twitter/post.php")
var request = URLRequest(url: url!)
request.httpMethod = "GET" <--- if i change this to POST, it is worked
let body = "id=\(id)"
request.httpBody = body.data(using: .utf8)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
if error == nil {
DispatchQueue.main.async {
self.activityIndicator.startAnimating()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
guard let parsedJSON = json else {
print ("error while parsing JSON")
return
}
print(parsedJSON)
} catch {
print ("Error : \(error)")
}
}
} else {
print ("Error : \(error!)")
}
})
task.resume()
}
这里出了什么问题?为什么它只在我使用 POST 方法而不是 GET 方法时有效?
您正在通过请求正文发送数据。默认情况下,aGET
将期望参数作为查询字符串参数,而 aPOST
将通过正文期望它们
https://secure.php.net/manual/it/function.http-get-request-body.php
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句