【问题标题】:Alamofire using query parameters status 500Alamofire 使用查询参数状态 500
【发布时间】:2017-05-03 19:57:05
【问题描述】:

我正在调用 Api 路线以使用经度、纬度和半径获取本地商店的分支机构。 api路线在邮递员上工作得很好。使用 Alamofire 它正在回复内部服务器错误 500。我怀疑问题出在参数中,但我只是测试了所有内容和每个组合都没有成功。

这是我的 HTTP 请求:

    let branchesRoute = "geo/services/"
//Get branches within location radius
    func getBranchesWithRadius (serviceID: Int, location: CLLocation, completion: @escaping (_ status:Bool, _ error:Error?, _ msg:String?, _ branches:NSArray?) ->())
    {

    let route = URL(string:branchIp + branchesRoute + String(serviceID) + "/branches")
    print(route)

    let header: HTTPHeaders = [

        "Content-Type":"application/json",
        "auth-token": Helper.shared.getApiKey()//"\(Helper.shared.getApiKey())"
    ]

    let params: Parameters = [
        "longitude" : location.coordinate.longitude,
        "latitude" : location.coordinate.latitude,
        "radius" : Helper.shared.getRadius()
    ]


    print(params)


    Alamofire.request(route!, method: .get, parameters: params, encoding: JSONEncoding.default, headers: header)
        .validate(statusCode: 200..<300)
        .responseJSON { (response) in
            switch response.result {
            case .success( _):
                let json = response.result.value!
                // let swiftyJson = JSON(json)
                completion(true, nil, nil, json as? NSArray)
                // print(json)

            case .failure(let err):
                print(err)
                if response.response?.statusCode == 401 {
                    completion(false,err,"Unauthorized",nil)
                } else {
                    completion(false, err, "Error getting branches",nil)
                }
            }
    }


}

这是我从邮递员那里呼叫的路线:

http://100.100.70.185:9090/geo/services/3/branches?longitude=31.331358000000002&latitude=30.082763&radius=1000000

当我在 swift 中使用print() 命令时,这些是我的结果:

print(params) = ["longitude": 31.331358000000002, "latitude": 30.082763, "radius": 100000]

print(route) =

Optional(http://100.100.70.185:9090/geo/services/3/branches)

关于Optional 我只是解开它route!

关于我在这里写的IP地址不是我使用的真实IP地址,以防你测试但它没有成功。

【问题讨论】:

  • 如果出现错误response.response.url与POSTMAN中的一样吗?
  • @Larme 这是response.url Optional(http://100.100.70.185:9090/geo/services/3/branches)
  • 缺少参数(response.url.absoluteString)?如果你把那个地址不带参数放在邮递员中,你有同样的 500 错误吗?
  • @Larme 是的,我肯定会遇到同样的错误。我对此进行了测试。我怀疑问题是因为我上面提到的参数,但我不知道代码语法有什么问题。
  • 试试URLEncoding.default而不是JSONEncoding.default

标签: json swift httprequest alamofire


【解决方案1】:

实际问题在于编码,您必须使用正确的ParameterEncoding,具体取决于您的 API 实现。

如果带有 HTTP 正文的编码请求的 Content-Type HTTP 标头字段设置为 application/x-www-form-urlencoded; charset=utf-8,则使用 URLEncoding

-

如果Content-Type HTTP 标头字段的 编码请求设置为application/json

-

如果Content-Type HTTP 标头字段为 编码请求设置为application/x-plist

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-05
    • 2018-01-30
    • 1970-01-01
    • 2021-08-07
    • 2017-07-06
    • 2019-02-25
    • 1970-01-01
    • 2021-12-05
    相关资源
    最近更新 更多