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

时间:2019-04-25 23:22:50

标签: ios swift alamofire

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

由于Alamofire文档以及Stack Overflow中提供的所有帮助,我试图使用ParameterEncoding自定义编码。

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

这是卷曲的例子:

卷曲-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)
}

“ 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。

预先感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

如上所述,您的请求正在使用邮递员或终端中的curl处理。以下是我得到的结果

enter image description here

如@Glenn所指出的那样,使用URL blih.epitech.eu/user/repositories访问浏览器的结果如下所示

enter image description here

我相信,您请求的网址有问题。

已编辑

请参见下图,了解其为何可以使用curl

enter image description here

  

尝试将您的请求发布一次,然后添加content-type = application/x-www-form-urlencoded,但不确定,但这可能会有帮助。

答案 1 :(得分:1)

只需替换JSON.encoding-> URLEncoding

Alamofire.request(path,method: .get, parameters: params, encoding: URLEncoding.default, headers: nil)

答案 2 :(得分:0)

尝试一下:

let url = "https://blih.epitech.eu/user/repositories"
let param = ["user":"asdfdsf",
    "signature":"password"]
if let jsonData = try? JSONEncoder().encode(param) {

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = HTTPMethod.post.rawValue
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData

    Alamofire.request(request).responseJSON {
        (response) in
        debugPrint(response)
    }
}

输出:

  

{      错误=“错误令牌”;   }

相关问题