我一直在尝试使用 swift 为移动应用程序向我的本地主机发送 HTTP 帖子,它打印 Result -> Optional(["user": larry])
这应该意味着它可以工作,但它没有在我的本地主机上发布任何内容。我的代码是:
func ReqUsers() -> Void {
let json = ["user":"larry"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let url = NSURL(string: "http://192.168.1.318:8080")! /*localhost*/
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
if error != nil{
print("Error -> \(String(describing: error))")
return
}
do {
let result = try JSONSerialization.jsonObject(with: /*data!*/ request.httpBody!, options: .allowFragments) as? [String:AnyObject]
print("Result -> \(String(describing: result))")
} catch {
print(response!)
print("Error -> \(error)")
print("that")
}
}
task.resume()
} catch {
print(error)
print("this")
}
print("called")
}
谢谢你的时间有关后端的更多信息,它是用 goLang 编写的,代码如下:
package main
import (
"fmt"
//"os"
//"io/ioutil"
//"log"
"net/http"
)
func main() {
http.HandleFunc("/", HelloServer)
http.ListenAndServe(":8080", nil)
}
func HelloServer(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello")
}
最佳答案
如果您在服务器中没有看到日志,可能是由 URLSession
引起的的缓存策略。
尝试设置 cachePolicy
您的属性(property)URLRequest
至 .reloadIgnoringLocalAndRemoteCacheData或 .reloadIgnoringCacheData看看是否有效:
let url = URL(string: "http://192.168.1.318:8080")! /*localhost*/
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
// or
request.cachePolicy = .reloadIgnoringCacheData
关于swift - http Post 说它可以工作,但它没有在本地主机上发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64618874/