Skip to content

Instantly share code, notes, and snippets.

@HomerJSimpson
Created October 19, 2015 21:25
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HomerJSimpson/80c95f0424b8e9718a40 to your computer and use it in GitHub Desktop.
Save HomerJSimpson/80c95f0424b8e9718a40 to your computer and use it in GitHub Desktop.
POST application/x-www-form-urlencoded via swift
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(true)
extension NSMutableURLRequest {
/// Percent escape
///
/// Percent escape in conformance with W3C HTML spec:
///
/// See http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
///
/// - parameter string: The string to be percent escaped.
/// - returns: Returns percent-escaped string.
private func percentEscapeString(string: String) -> String {
let characterSet = NSCharacterSet.alphanumericCharacterSet().mutableCopy() as! NSMutableCharacterSet
characterSet.addCharactersInString("-._* ")
return string
.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)!
.stringByReplacingOccurrencesOfString(" ", withString: "+", options: [], range: nil)
}
/// Encode the parameters for `application/x-www-form-urlencoded` request
///
/// - parameter parameters: A dictionary of string values to be encoded in POST request
func encodeParameters(parameters: [String : String]) {
HTTPMethod = "POST"
let parameterArray = parameters.map { (key, value) -> String in
return "\(key)=\(self.percentEscapeString(value))"
}
HTTPBody = parameterArray.joinWithSeparator("&").dataUsingEncoding(NSUTF8StringEncoding)
}
}
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
]
let session = NSURLSession(configuration: config)
let request = NSMutableURLRequest(URL: NSURL(string:"https://XXXXX.com/mobile-helper.jsp")!)
request.encodeParameters(["name" : "user.name@not.local", "passwd":"Passwd123"])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
print(error)
return
}
print(JSON(data:data!))
}
task.resume()
@edw
Copy link

edw commented Apr 18, 2018

This is super-useful code. Would you mind explicitly placing it under an MIT, BSD, LGPL, or similar license?

@janeshsutharios
Copy link

@edw You are right ! what a workaround 👍 )

@rahul-inspired-iosdeveloper

@drhr

Thanks for the answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment