【发布时间】:2019-09-15 10:47:57
【问题描述】:
自 3 周以来我一直面临一个问题,我正在使用一个非常特殊的 API,它需要一个 JSON 对象作为 GET 请求中的主体。我认为这是主要问题
感谢 Alamofire 文档和 Stack Overflow 中提供的所有帮助,我尝试使用 ParameterEncoding 自定义编码,但仍然没有成功。
当我在终端中使用 Postman 或 curl 发出请求时,没有问题,但是当我使用 Alamofire 快速开发时,我收到内部错误 500 或响应中没有传递任何内容(当我在我的带有关键字 encoding 的请求函数:JSONEncoding.default)。
这是 curl 的例子:
curl -X 获取https://blih.epitech.eu/user/repositories -H '内容类型:应用程序/json' -d '{"user": 帐号, "signature": 密码}'
这是我的代码示例:
/// swift 5
let userString = #"{"user":"\#(account)","signature":"\#(signaturePassword)"}"#
let urlString = "https://blih.epitech.eu/repositories"
Alamofire.request(urlString, method: .get, parameters: [:], encoding: JSONStringArrayEncoding.init(string: userString), headers: nil)
.responseJSON { (response) in
debugPrint(response)
}
“JSONStringArrayEncoding”是我的自定义编码结构:
struct JSONStringArrayEncoding: ParameterEncoding {
private let myString: String
init(string: String) {
self.myString = string
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
let data = Data(myString.utf8)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
return urlRequest
}
}
我希望在请求成功时有一个 json 数组:
{
"message": "Listing successful",
"repositories": {
"aaaa": {
"uuid": "e3a6bea1-c581-5fde-a3a8",
"url": "https://blih.epitech.eu/repository/aaa"
}
}
}
但我收到内部错误 500。
提前感谢您的帮助。
【问题讨论】:
-
您是否尝试过在浏览器中访问您的网址? blih.epitech.eu/user/repositories
-
当然,我在 Swift 中开发时有时会遇到同样的错误,但是当我使用 postman 或 curl 命令进行测试时,没有问题。我应该准确地说您需要在正文中发送一个对象:{"user":"test@epitech.eu", "signature":"long-token"}