简体   繁体   中英

Alamofire error request with parameter without name

I'm getting an error while trying to encode a parameter into a request url.

Here is my function to get the request url:

func asURLRequest() throws -> URLRequest {
        let url = try baseURL.asURL().appendingPathComponent(path)
        var request = URLRequest(url: url)
        request.method = method
        if method == .get {
            request = try URLEncodedFormParameterEncoder().encode(parameters, into: request)
        } else if method == .post {
            request = try JSONParameterEncoder().encode(parameters, into: request)
            request.setValue("application/json", forHTTPHeaderField: "Accept")
        }
        return request
    }

It is working when the parameter is a dictionary like ["id": 1]. The url would be: http://.../api/v1/items/?id=1

I want to pass the parameter 1 only, so the url would be like this: http://.../api/v1/items/1

But it doesn't work, I get this error from Alamofire:

requestRetryFailed(retryError: Alamofire.AFError.requestRetryFailed(retryError: Alamofire.AFError.parameterEncoderFailed(reason: Alamofire.AFError.ParameterEncoderFailureReason.encoderFailed(error: Alamofire.URLEncodedFormEncoder.Error.invalidRootObject("string("1")")))

What you want is a path encoding, not a query encoding or form encoding. There is no specific parameter encoder in Alamofire for path components (though there is an ongoing feature request). Usually people encode them into the path directly, so you can modify your code to do so directly by using a router and having each route encode its own parameters.

func encodeParameters(into request: URLRequest) throws -> URLRequest {
  switch self {
  case .someRoute(parameters):
    return try URLEncodedFormParameterEncoder().encode(parameters, into: request)
  case .pathParameterRoute(parameter):
    var request = request
    request.url?.appendPathComponent(parameter)

    return request
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM