我一直在尝试使用 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 mainimport ( "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")}
1 回答
撒科打诨
TA贡献1934条经验 获得超2个赞
如果您在服务器中看不到日志,可能是由URLSession的缓存策略引起的。
尝试将cachePolicy您的属性设置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
- 1 回答
- 0 关注
- 133 浏览
添加回答
举报
0/150
提交
取消