使用Moya和Alamofire时使用参数编码的发布请求错误

编程入门 行业动态 更新时间:2024-10-20 16:09:53
本文介绍了使用Moya和Alamofire时使用参数编码的发布请求错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用moya发出发布请求,但是当我发送发布时,服务器给我一个错误,它无法解码主体参数.我使用URLEncoding.default对这样的参数进行编码

I use the moya make the post request,but when I send the post , the server give me an error, it can't decoding the body parameters.I use URLEncoding.default to encode the parameters like this

public var parameterEncoding: ParameterEncoding { return URLEncoding.default }

它将设置内容类型application/x-www-form-urlencoded,并且服务器接受的内容类型也相同

It will set the content-type application/x-www-form-urlencoded, and the server accept content type is same too

如果参数是类似{"a":"b"}的字典,则效果很好,但是如果字典包含数组或其他字典,则服务器无法从请求正文中获取参数.

if parameters is a dictionary like this {"a":"b"} ,that is working well, but if dictionary contained array or another dictionary ,the server can't get the parameters from request body.

EX:

{ "a":"xxx", "b":[ "xxxxx", "xxxxx" ] }

alamofire会像这样编码 "a" ="xxx"& b [] = xxxx& b [] = xxx

alamofire will encode this like "a"="xxx"&b[]=xxxx&b[]=xxx

但是服务器期望a = xxx& b [0] = xxx& b [1] = xxxx

but the server expect a=xxx&b[0]=xxx&b[1]=xxxx

如何解决这个问题?

推荐答案

您可以手动构建参数字符串,然后将参数字符串链接到Url字符串.最后,只需由Alamofire发出带有网址的请求,而无需任何参数(它们已经在网址中).

You can build the parameter string manually, and then link the parameter string to Url string. Finally, just make request with url by Alamofire, without any parameters(they are in url already).

构建参数字符串的方式:

The way to build parameter string:

let dict = ["a":"xxx","b":["xxx","xxxxxxx"]] as [String : Any] var paramString = "" for key in dict.keys { let value = dict[key] if let stringValue = value as? String { paramString += "&\(key)=\(stringValue)" } else if let arr = value as? Array<String> { for i in 0 ... arr.count - 1 { paramString += "&\(key)[\(i)]=\(arr[i])" } } else{ //other type? } } if paramString.characters.count > 0 { paramString = paramString.substring(from: paramString.index(paramString.startIndex, offsetBy: 1)) } print(paramString) //output is: b[0]=xxx&b[1]=xxxxxxx&a=xxx

更多推荐

使用Moya和Alamofire时使用参数编码的发布请求错误

本文发布于:2023-11-26 06:55:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633091.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   参数   Moya   Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!