Trouble with NSURLSession multipart/form-data post request - ios

Im having some trouble with sending text and images in the same post request to my server. I think the problem has to do with the way i set my boundary.
Im using swift with ios9.
I followed instructions here ios Upload Image and Text using HTTP POST
doing my best to convert the obj-c into swift
however when i post a request to my server, whenever i try to access the post data such as $_POST["key"] i get an undefined index error. Here is the code i use to setup the http request, can anyone spot the error:
func sendRegisterRequest(params:Dictionary<String, String>, withImage image: UIImage) {
// https://stackoverflow.com/questions/8564833/ios-upload-image-and-text-using-http-post
let url = NSURL(string: "MY_URL");
let request = NSMutableURLRequest(URL: url!)
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
let boundaryConstant = "----------V2ymHFg03ehbqgZCaKO6jy--";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
let fileParamConstant = "file";
request.HTTPMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundaryConstant)", forHTTPHeaderField: "Content-Type")
// post body
let body = NSMutableData();
// add params (all params are strings)
for (key, value) in params {
body.appendData("\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
body.appendData("Content-Disposition: form-data; name=\"\(key.stringByAddingPercentEncodingWithAllowedCharacters(.symbolCharacterSet())!)\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
body.appendData("\(value.stringByAddingPercentEncodingWithAllowedCharacters(.symbolCharacterSet())!)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
}
//print(body);
// add image data
let imageData = UIImageJPEGRepresentation(image, 1.0);
body.appendData("\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
body.appendData("Content-Disposition: form-data; name=\"\(fileParamConstant)\"; filename=\"image\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
body.appendData(imageData!);
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
body.appendData("\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
request.HTTPBody = body;

When you use multipart form data, you must prefix the boundary with an additional two hyphens within the body data, and you must also add two hyphens at the end of the final boundary. So if you have:
boundary=foo
then the body should look like this:
--foo
field 1 info
--foo
field 2 info
--foo--
See also What is the '-' in multipart/form-data?

Related

How to get a MS Translator access token from Swift 3?

I am trying to work with a MS Translator API from Swift 3 (right now playing in playgrounds, but the target platform is iOS). However, I got stuck when I was trying to get an access token for OAuth2. I have following code (I tried to port the code from example at Obtaining an access token):
let clientId = "id".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let clientSecret = "secret".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let scope = "http://api.microsofttranslator.com".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let translatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
let requestDetails = "grant_type=client_credentials&client_id=\(clientId)&client_secret=\(clientSecret)&scope=\(scope)"
let postData = requestDetails.data(using: .ascii)!
let postLength = postData.count
var request = URLRequest(url: URL(string: translatorAccessURI)!)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("\(postLength)", forHTTPHeaderField: "Content-Length")
request.httpBody = postData
URLSession.shared.dataTask(with: webRequest) { (returnedData, response, error) in
let data = String(data: returnedData!, encoding: .ascii)
print(data)
print("**************")
print(response)
print("**************")
print(error)
}.resume()
Of course, I used a valid clientId and a valid clientSecret.
Now the callback prints following information. First, the returnedData contain a message that the request was invalid, along with a following message:
"ACS90004: The request is not properly formatted."
Second, the response comes with a 400 code (which fits the fact that the request is not properly formatted).
Third, the error is nil.
Now I was testing the call using Postman, and when I used the same URI, and put the requestDetails string as a raw body message (I added the Content-Type header manually), I got the same response. However, when I changed the body type in Postman UI to application/x-www-form-urlencoded and typed in the request details as key value pairs through its UI, the call succeeded. Now it seems that I am doing something wrong with the message formatting, or maybe even something bad with the Swift URLRequest/URLSession API, however, I cannot get a hold on to what. Can somebody help me out, please? Thanks.
OK, so after some more desperate googling and experimenting I have found my error. For the future generations:
The problem resided in encoding the parameters in the body of the PUT http request. Instead of:
let scope = "http://api.microsofttranslator.com"
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
I have to use the following:
let scope = "http://api.microsofttranslator.com"
.addingPercentEncoding(withAllowedCharacters:
CharacterSet(charactersIn: ";/?:#&=$+{}<>,").inverted)!
Seems that the API (or the HTTP protocol, I am not an expert in this) have problems with / and : characters in the request body. I have to give credit to Studiosus' answer on Polyglot issue report.

iOS swift post request with binary body

I want to make a POST request from iOS (swift3) which passes a chunk of raw bytes as the body. I had done some experimenting which made me thought the following worked:
let url = URL(string: "https://bla/foo/bar")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = Data(hex: "600DF00D")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
"DATA \(data ?? Data()) RESPONSE \(response) ERROR \(error)".print()
}
task.resume()
Didn't know it was a problem until I tried sending something simple like a single 0xF0. At which point my tornado server started complaining that I was sending it
WARNING:tornado.general:Invalid x-www-form-urlencoded body: 'utf-8' codec can't decode byte 0xf0 in position 2: invalid continuation byte
Am I just supposed to set some header somehow? Or is there something different I need to do?
The two common solutions are:
Your error message tells us that the web service is expecting a x-www-form-urlencoded request (e.g. key=value) and in for the value, you can perform a base-64 encoding of the binary payload.
Unfortunately, base-64 strings still need to be percent escaped (because web servers generally parse + characters as spaces), so you have to do something like:
let base64Encoded = data
.base64EncodedString(options: [])
.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
.data(using: String.Encoding.utf8)!
var body = "key=".data(using: .utf8)!
body.append(base64Encoded)
var request = URLRequest(url: url)
request.httpBody = body
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print(error!)
return
}
...
}
task.resume()
Where:
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]#" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)
return allowed
}()
}
For more discussion on that character set, see point 2 in this answer: https://stackoverflow.com/a/35912606/1271826.
Anyway, when you receive this on your server, you can retrieve it as and then reverse the base-64 encoding, and you'll have your original binary payload.
Alternatively, you can use multipart/formdata request (in which you can supply binary payload, but you have to wrap it in as part of the broader multipart/formdata format). See https://stackoverflow.com/a/26163136/1271826 if you want to do this yourself.
For both of these approaches, libraries like Alamofire make it even easier, getting you out of the weeds of constructing these requests.

Differences between Using NSJSONSerialization.dataWithJSONObject and dataUsingEncoding to make up the HTTP body in Swift

I have seen two kinds of methods to make up the HTTP body.
First one is:
let url = NSURL(string: "http://example.com")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let postString = "id=13&name=Jack"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
Second one is:
let url = NSURL(string: "http://example.com")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let params = ["id":"13", "name":"Jack"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
When I directly print out the request.HTTPBody the data is different. So I am wondering are there any differences between these two methods in terms of the implementation of the server side? Assuming I'am using PHP.
there're two format data.
in code using postString.dataUsingEncoding it will send data in urlencoded format. In client you must set request's Content-Type header to "application/x-www-form-urlencoded" or something like "application/x-www-form-urlencoded charset=utf-8"
in code using NSJSONSerialization.dataWithJSONObject it will send data in json format. In client you must set request's Content-Type header field to "application/json"
I'm iOS dev so I don't know about format's effect to server side PHP. to answer your question you must find difference between application/x-www-form-urlencoded and application/json format in server side

How to set HTTPBody?

In Swift I'm trying to make a post request (using the NSURLSession) to sign in a user to a WebAPI web services.
The Url is www.myurltest.com/Token and I must pass the following string as POST body:
grant_type=password&username=MyUsername&password=MyPassword.
So in Swift I've make:
let session = NSURLSession.sharedSession();
let url = NSURL(string:"www.myurltest.com/Token");
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
Now I want to set the POST body (that is a string) but I don't know how:
request.HTTPBody = ?????
Thanks.
You're almost there, you just need to turn the string into an NSData object. If your string is in a variable named body, your code will look like request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)

Upload image into asp.net web service in swift

How can I upload an image into my web service then I can save it on my server!
I have tried the below code using POST method but I got this error
(A potentially dangerous Request.Form value was detected from the client (uploadFile="<ffd8ffe0 00104a46 4...").)
func myImageUploadRequest() {
let imageData = UIImageJPEGRepresentation(myImageView, 1)
let boundary = generateBoundaryString()
var base64String = imageData.base64EncodedStringWithOptions(.allZeros)
let myUrl = NSURL(string: "http://xxxxx/UploadImageTest");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
if(imageData==nil) { return; }
var body = NSMutableData();
body.appendString("uploadFile=\(imageData)")
request.HTTPBody = body
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
// You can print out response object
println("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("****** response data = \(responseString!)")
dispatch_async(dispatch_get_main_queue(),{
});
}
task.resume()
}
And this the POST SOAP on my Asp.net web service
POST /xxxx.asmx/UploadImageTest HTTP/1.1
Host: xxxx.com
Content-Type: application/x-www-form-urlencoded Content-Length: length
uploadFile=string&uploadFile=string
The error was sending NSData to Asp.net web service.
convert the image int base64 using this code
let imageData = UIImageJPEGRepresentation(myImageView, 1)
var base64String = imageData.base64EncodedStringWithOptions(.allZeros)
then send it to web service and make sure in your web service receive String data, not byte() array.
in your web service convert the base64 into Image and save into your server.
That's it!.
I am not familiar with Swift but in Objective C I would have prepared data something like this:
....
NSMutableString* body = [NSMutableString new];
[body appendFormat:#"uploadFile=%#",base64String];
....
The reason it is erring out is pretty obvious from the error description. You might find your code is formatting your base64 image string as
uploadFile="<ffd8ffe0 00104a46 4...
The text after uploadFile= is not at all a base64 encoded string rather the string representation of NSData and that extra < at the starting of the data is being treated as a html tag in server. ASP.NET request validation does not allow such tags in your request body as security measure, to prevent code/script injection and cross site scripting.
Even if you disable request validation from server web.config or .asmx the data would still not be interpreted by server as it would still not be in valid base64 format as the server might expect.
So my advice is to frame your request properly before sending it to server and everything should work seamlessly.

Resources