swift - http Post 说它可以工作,但它没有在本地主机上发布

标签 swift http go post

我一直在尝试使用 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/

相关文章:

mongodb - 如何将mongodb go driver的primitive.Timestamp类型转换回Golang time.Time类型?

python - 如何在 Golang 中运行外部 Python 脚本?

docker - redis HMSEET出现错误,调用tcp :6379: connect: connection refused

ios - QLPreviewController 不适用于 iOS11

ios - 使用 swift 客户端库时服务器 Socket.io 回调崩溃

asp.net - 如何安全地引用 https 页面上的 http 资源?

http - HTTP header If-None-Match : * mean?是什么意思

ios - 将导航 Controller 嵌入到选项卡栏 Controller 中

objective-c - NSString 和 Swift.String 上的 ReplaceCharactersInRange 之间有区别吗

JAVA Rest-Assured DSL 重定向不工作