如何使用 Alamofire 在 get 请求中发送 JSON 正文

Gui*_*Mnt 3 ios swift alamofire

三周以来我一直面临一个问题,我正在使用一个非常特殊的 API,它需要一个 JSON 对象作为 GET 请求中的正文。我认为这是主要问题

我尝试使用 ParameterEncoding 自定义编码,感谢 Alamofire 文档以及 Stack Overflow 中提供的所有帮助,但仍然没有成功。

当我在终端中使用 Postman 或curl 发出请求时,没有问题,但是当我使用 Alamofire 快速开发时,我收到内部错误 500 或响应中没有传递任何内容(当我在请求函数中设置参数时)关键字编码:JSONEncoding.default)。

这是卷曲示例:

curl -X GET https://blih.epitech.eu/user/repositories -H '内容类型:application/json' -d '{“用户”:帐户,“签名”:密码}'

这是我的代码示例:

/// 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)
}
Run Code Online (Sandbox Code Playgroud)

“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
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望请求成功时有一个 json 数组:

{
"message": "Listing successful",
    "repositories": {
        "aaaa": {
            "uuid": "e3a6bea1-c581-5fde-a3a8",
            "url": "https://blih.epitech.eu/repository/aaa"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我收到内部错误 500。

预先感谢您的帮助。

Muh*_*kif 5

只需替换JSON.encoding->URLEncoding

Alamofire.request(path,method: .get, parameters: params, encoding: URLEncoding.default, headers: nil)
Run Code Online (Sandbox Code Playgroud)