使用Alamofire格式化HTTP请求“format = json&body =”

问题描述 投票:0回答:2

我正在尝试发送需要看起来像这样的api请求:

https://api.gibbly.com/1/device?format=json&body= { “选择”= { “selectionType”: “注册”, “selectionMatch”: “”, “includeRuntime”:真}}

但是,当我使用下面的代码时,我收到一个错误。在响应的[RESULT]段中,我得到以下内容:

[RESULT] FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

我已经尝试使用Postman的请求,它工作正常所以我认为问题是由代码引起的。

根据代码中的第一个“print”语句,HTTP正文似乎是正确的:

Optional({"selection":{"selectionType":"registered","selectionMatch":"","includeSettings":true}})

我唯一能想到的是Alamofire没有在请求中添加“format = json&body =”,但我无法弄清楚如何查看是否是这种情况。任何帮助,将不胜感激。


        let headers: HTTPHeaders = [
            "Authorization": "Bearer adsf023494axadf32342",
            "Content-Type": "text/json"
        ]

        let parameters: [String: Any] = [
            "selection":[
                "selectionType":"registered",
                "selectionMatch":"",
                "includeSettings":true
            ]
        ]

        Alamofire.request(url!, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON {
            response in
print(NSString(data: (response.request?.httpBody)!, encoding: String.Encoding.utf8.rawValue))
            print(response)
        }
swift httprequest alamofire
2个回答
0
投票

对于GET方法,在Alamofire请求中使用URLEncoding.default而不是JSONEncoding.default


0
投票

好想通了。我做了以下工作:(1)将参数创建为字符串,(2)百分比编码,以便所有字符都可以用作网址,(3)将编码参数添加到基本网址,(4)使用带有基本网址的新网址,然后编码参数作为我的请求的网址。

let url = "https://api.gibbly.com/1/device?format=json&body="
        let urlParams = "{\"selection\":{\"selectionType\":\"registered\",\"selectionMatch\":\"\",\"includeSettings\":true}}"
        let urlEncoded = url + urlParams.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

        let headerList : HTTPHeaders = [
            "Authorization" : "Bearer " + (KeychainWrapper.standard.string(forKey: "accessToken"))!, 
            "Content-Type" : "text/json"
        ]

        Alamofire.request(urlEncoded, method: .get, headers: headerList).responseJSON{
            response in
print(response)
}
© www.soinside.com 2019 - 2024. All rights reserved.