Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift post request encoding plus sign become white space

Tags:

ios

swift

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)
}}}}
like image 683
user3566769 Avatar asked Apr 26 '16 03:04

user3566769


1 Answers

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")

like image 54
Manuel Avatar answered Nov 15 '22 09:11

Manuel