可能是很愚蠢的事情,但是我挠头想知道为什么会这样。我的机器上本地运行着一个小的Flask REST服务器,我正在发布一些JSON数据。当我使用POSTMAN进行检查时,它工作正常,但是当我使用以下代码调用POST时,出现错误-无法连接到服务器。我到底在做什么错?我检查了网址的格式是否正确。
func postJSONPayload(payload: Data, completion: ((Error?) -> Void)?) {
print("Posting JSON Payload to server........")
var urlComponents = URLComponents()
urlComponents.scheme = "http"
urlComponents.host = "127.0.0.1"
urlComponents.port = 5000
urlComponents.path = "/mobir/api/payloads"
guard let url = urlComponents.url else {fatalError("Could not create url from components!")}
print("url is: \(url.absoluteString)")
var request = URLRequest(url: url)
request.httpMethod = "POST"
var headers = request.allHTTPHeaderFields ?? [:]
headers["Content-Type"] = "application/json"
request.allHTTPHeaderFields = headers
request.httpBody = payload
print("payload: ", String(data: request.httpBody!, encoding: .utf8) ?? "No payload in body!")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: url) { (responseData, response, responseError) in
print("got the response!")
guard responseError == nil else {
print("responseError not nil- error is: \(responseError!.localizedDescription)")
completion?(responseError!)
return
}
if let data = responseData, let utf8repofData =
String(data: data, encoding: .utf8) {
print("response: ", utf8repofData)
} else {
print("No data to read in response!")
}
}
task.resume()
}
答案 0 :(得分:0)
好的,这很愚蠢-我自己回答。需要将y
放入我的Flask服务器代码中,以便在URL包含计算机的IP地址时在网络上可见。现在可以工作。