使用Moya和Alamofire时使用参数编码的发布请求错误 [英] Post request error with parameter encode when use moya and alamofire

查看:465
本文介绍了使用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时使用参数编码的发布请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆