我有一个 API,它返回一个非常简单的 JSON。
首先,包含 api 的服务器位于我的本地计算机 (localhost) 中,在这种情况下,一切正常。
我将 api 传递到网络托管,当我尝试从 iPhone 应用程序(使用 Alamofire)连接到托管 api 时不起作用
Alamofire.request(.POST, "https://domain.com/api/search", parameters: ["ubicacion": ubicacionId, "fecha":"\(dateFormatter.stringFromDate(fecha))"], encoding: .URL)
.responseJSON { response in
switch response.result {
case .Success:
print(response.request) // original URL request
print(response.response) // URL response
print(response.result) // result of response serialization
self.JSON = response.result.value!
//llamar el delegate
self.delegate.devolverjson(self.JSON)
case .Failure(let error):
print(response.request) // original URL request
print(response.response) // URL response
print(response.result) // result of response serialization
self.JSON = ["error":error]
//llamar el delegate
self.delegate.devolvererror(self.JSON)
}
}
在这种情况下,response.response
是:
{ URL: https://domain.com/api/search } { status code: 405, headers {
"Cache-Control" = "no-cache, private";
Connection = "Keep-Alive";
"Content-Type" = "text/html; charset=UTF-8";
Date = "Thu, 07 Jul 2016 18:24:26 GMT";
"Keep-Alive" = "timeout=3, max=30";
Server = "Apache Phusion_Passenger/4.0.10 mod_bwlimited/1.4 mod_fcgid/2.3.9";
"Transfer-Encoding" = Identity;
"X-Powered-By" = "PHP/5.6.22";
allow = POST;
} })
response.result
为 .Failure
错误是
error: {
error = "Error Domain=NSCocoaErrorDomain Code=3840 \"Invalid value around character 0.\" UserInfo={NSDebugDescription=Invalid value around character 0.}";
}
当我从 Postman 连接到 api(相同的 URL: https://domain.com/api/search )时,api 返回正确的信息 (JSON),其中包含此 header 。
Cache-Control →no-cache
Connection →Keep-Alive
Content-Type →application/json
Date →Thu, 07 Jul 2016 18:23:38 GMT
Keep-Alive →timeout=3, max=30
Server →Apache Phusion_Passenger/4.0.10 mod_bwlimited/1.4 mod_fcgid/2.3.9
Transfer-Encoding →chunked
X-Powered-By →PHP/5.6.22
为什么如果该 API 适用于 Postman,则不适用于 Alamofire?
如果英文不正确,请原谅
最佳答案
我今天也遇到了类似的问题。我的解决方法是更改请求的编码。
我在 URLEncoding()
和 JSONEncoding.default
之间切换
您可以尝试适合您的请求的各种其他编码。
关于swift - 请求 REST POST API 在 Postman 中工作,但在 Alamofire 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38253285/