我一直在嘗試使用 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 關注
- 160 瀏覽
添加回答
舉報
0/150
提交
取消