问题
when post A+
or O+
or any (+) bloods types with +
character, I receive a "not valid blood" error.
The blood
value is in JSON
dictionary: How do I post +
character in Alamofire?
let dictionary = ["fname": "name",
"lname": "family",
"blood": "A+"]
let updateData = try! JSONEncoder().encode(dictionary)
let jsonString = String(data: updateData, encoding: .utf8)!
var components = URLComponents(string: registerUrl)!
components.queryItems = [
URLQueryItem(name: "api_key", value: apiKey),
URLQueryItem(name: "profile", value: jsonString)
]
Alamofire.request(components.url!, method: .post).responseJSON {
response in
if response.result.isSuccess {
let json: JSON = JSON(response.result.value!)
print(json)
}
}
回答1:
Unfortunately, URLComponents
will not percent encode +
character although many (most?) web services require it to be (because, pursuant to the x-www-form-urlencoded
spec, they replace +
with space character). When I posted bug report on this, Apple's response was that this was by design, and that one should manually percent encode the +
character:
var components = URLComponents(string: "https://www.wolframalpha.com/input/")!
components.queryItems = [
URLQueryItem(name: "i", value: "1+2")
]
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
Obviously, if you were doing a standard application/json
request, with the JSON in the body of the request, no such percent encoding is needed. But if you're going to include the JSON in the URL like this, then you will have to percent encode the +
character yourself.
Alternatively, you can let Alamofire do this for you:
let parameters = [
"api_key": apiKey,
"profile": jsonString
]
Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in
...
}
This, admittedly puts the properly percent encoded value in the body of the POST
request, not the URL as in your example, but generally in POST
requests, that's what we want.
来源:https://stackoverflow.com/questions/48660345/how-to-post-parameter-with-plus-sign-in-alamofire