Recently I found out that when I send a post data which include a "+" sign, the "+" will become white space. for example { dish_name: fish+chips }. This cause server side cannot read data. So I try following, I use :
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
to encoding my request to UTF-8.However, this line cause my post data become empty. I have no clue why this happen. Or is there any better solution to keep "+" sign as itself during post method?
func PostMethod(url:NSURL,Data:String) {
let request = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let submitContent = Data
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = submitContent.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
//print("——request——")
//print(request)
let task = session.dataTaskWithRequest(request){
data, response, error in
if data != nil{
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
print(responseString)
let jsonall = self.commonControl.StringToJson(responseString)
if let dataFromString = jsonall["body"].stringValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
}}}}
You can try convert your + into its ASCII code. For example:
let content = exampleString.stringByReplacingOccurrencesOfString("+", withString: "%2B", options: [], range: nil)
Swift 3+
let content = exampleString.replacingOccurrences(of: "+", with: "%2B")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With