NSMutableURLRequest remove "+" sign from request - ios

I am developing an iOS app which required to send phone number on server.
When I pass number without "+" it is work fine, but when I pass number with "+" sign (+123456, +234567) then it send number like (" 123456"," 234567").
It replace "+" by " " (space).
I convert NSDictionary into JsonData .
NSError *err;
NSData *data=[NSJSONSerialization dataWithJSONObject:mdict options:0 error:&err];
NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *strjson=[NSString stringWithFormat:#"GetData=%#",str];
NSLog(#"strjson=%#",strjson);
My code to build NSMutableRequest object.
NSURL *url = [NSURL URLWithString:urlString];
__weak NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soadMessage length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[soadMessage dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField: #"Content-Type"];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[_connection start];
Any help will be appreciated.

Try to escape your string with the CFURLCreateStringByAddingPercentEscapes
+ (NSString *)escapeValueForURLParameter:(NSString *)valueToEscape {
if (![valueToEscape isKindOfClass:[NSString class]]) {
valueToEscape = [(id)valueToEscape stringValue];
}
return (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef) valueToEscape,
NULL, (CFStringRef) #"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8);
}

You need to format the value of mdict to take out the + character. Or you could also trim it from the JSON at the end. Either way you will get the desired result.
Something like this:
mdict["Phone"].value = [mdict["Phone"].value stringByReplacingOccurrencesOfString:#"+"
withString:#""];
This is pseudocode but you get the idea. After doing this you can do the serialization and it should be fine.

Related

How to Send JSON String with Special Charaters in iOS?

I'm new to iOS and i'm using the following code to make API Calls.
-(NSData *)sendDataToServer:(NSString*)url :(NSString*)params
{
NSString *postDataString = [params stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"postDataString :%#",postDataString);
NSData *postData = [postDataString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlReq = [NSString stringWithFormat:#"%#", url];
[request setURL:[NSURL URLWithString:urlReq]];
[request setTimeoutInterval:180];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response in Server: %#",responseString);
return responseData;
}
I'm sending the following string as params to the above method. If I send the following data without special characters, I'm getting the success response.
If i Add any special charters as like (&) with json I'm always getting the invalid response, that is the server always returns null.
So Can anyone please provide any suggestion to get the right response when using json string with Special characters like '&' etc.,
submited_data={"safty_compliance_fields":[{"safty_compliance_id":"641","fieldName":"sc1","fieldType":"editText","fieldValue":"wedgies Ig"},{"safty_compliance_id":"642","fieldName":"sc2","fieldType":"editText","fieldValue":"het &"}],"status_id":"2","product_detail":[{"dynamic_fields_id":"639","fieldName":"p1","fieldType":"editText","fieldValue":"data1"},{"dynamic_fields_id":"640","fieldName":"p2","fieldType":"editText","fieldValue":"data2"}],"inspection_id":"3","second_level":[{"questions":[{"checkListValue":"NO","checkListCommentValue":"Jgkjgjkj","sub_category_id":"452","checkListName":"sl1"},{"checkListValue":"YES","checkListCommentValue":"jk","sub_category_id":"453","checkListName":"sl2"},{"checkListValue":"YES","checkListCommentValue":"gh","sub_category_id":"455","checkListName":"sl3"},{"checkListValue":"YES","checkListCommentValue":"nm","sub_category_id":"456","checkListName":"sl4"}],"title":"sl1","entity_second_level_entry_id":"130"},{"questions":[{"checkListValue":"YES","checkListCommentValue":"Bonn","sub_category_id":"454","checkListName":"s22"}],"title":"s211","entity_second_level_entry_id":"131"}],"comment":"Jgkjgjkj","status":"Ongoing"}
You didn't post the percent encoded string, but the original string.

Http Post parameters to url don't send special characters "+" in objectC Xcode

I have create an application that send two POST parameters to aspx server and it's save data in database.
It's an Iphone Application.
Here's the code:
NSString *post = [NSString stringWithFormat:#"name=%#&number=%#",
name,number];
NSString *capturedpost = [post
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *postData = [capturedpost dataUsingEncoding:NSUTF8StringEncoding];
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData
length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http:/www.myurl.aspx"]];
[request setHTTPMethod:#"POST"];
//[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request
returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler
bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
But on server, the string "number" that contain the telephone number like "+393333..." save in db the number without the "+".
How can I do?
The server side works fine, because the same App on Android that do same request work perfect!
OK, thanks to "holex" I successfully encode the URL in this way:
NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)post,
NULL,
(CFStringRef)#"+",
kCFStringEncodingUTF8 ));
And the "+" saved correctly in db!

Send POST request with special characters iOS

My app calls a web service to login. Usually the service works without any problems, but when I've a password with a special characters (example: !*'\"();:#&=+$,/?%#[]%), the web server doesn't allow me to login because on server side I receive the password without special characters for example:
password insert on my app: test+test
password receive to web server: testtest
As you see the request delete the special characters actually I'm sending the login credential by using the following code:
- (id)sendRequestToURL:(NSString *)url withMethod:(NSString *)method withUsername:(NSString*)username withPassword:(NSString*)password andInstallationId:(NSString*)installationId {
NSURL *finalURL = [[NSURL alloc]init];
if ([method isEqualToString:#"POST"]) {
finalURL = [NSURL URLWithString:url];
} else {
NSLog(#"Metodo no previsto");
}
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#&installationId=%#", username, password, installationId];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)postData.length];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:finalURL];
[request setHTTPMethod:method];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
[connection start];
}
return connection;
}
How I can fix this issue? I looked at the NSString class reference, I saw there's the method - stringByAddingPercentEncodingWithAllowedCharacters: to don't delete the special characters, does anyone know how to use this method? Can you show me a code snippet?
Thank you
I found a way to solve this issue, below is my code, maybe it should be useful for someone:
- (id)sendRequestToURL:(NSString *)url withMethod:(NSString *)method withUsername:(NSString*)username withPassword:(NSString*)password andInstallationId:(NSString*)installationId {
NSURL *finalURL = [[NSURL alloc]init];
if ([method isEqualToString:#"POST"]) {
finalURL = [NSURL URLWithString:url];
} else {
NSLog(#"Metodo no previsto");
}
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789"];
NSString *encodedPassword = [password stringByAddingPercentEncodingWithAllowedCharacters:set];
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#&installationId=%#", username, encodedPassword, installationId];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)postData.length];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:finalURL];
[request setHTTPMethod:method];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
[connection start];
}
return connection;
}
In this way I search in the password string the special characters and if it found it change this character with the percent encoding. In that way I can log in with plain password and with password with special characters. I hope it will be useful for someone.
Just encode every parmeter with the - stringByAddingPercentEscapesUsingEncoding:.
NSString *encodeUsername = [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodePassword = [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodeInstallationId = [installationId stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#&installationId=%#", encodeUsername, encodePassword, ins encodeInstallationId allationId];
And use this encoded paramater in your request.
Url encode your string and POST to web service. Please use below method for url encoding.
+(NSString *) urlencode: (NSString *) str {
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)str,
NULL,
(CFStringRef)#" ",
kCFStringEncodingUTF8 );
return [encodedString autorelease];
}

iOS - Extra param in POST request

I am new on iOS development. I try to send POST JSON to my RoR server.
It is my code:
params - some NSDictionary -> { uid = 123 }
NSData *postData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
NSString *urlString = [[NSString alloc] initWithFormat:#"%#%#", API_URL, url];
NSURL *nsUrl = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:nsUrl];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu",
(unsigned long)postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
At the end in the server I see:
{"uid"=>"123",
"action"=>"mAction",
"controller"=>"mController",
"token"=>{"uid"=>"123"}}
Why I see 'extra token' and how I can remove it ?
there is no reason I can see for the extra "token" to be there, so I would suggest that either the token was in the param all along, or that the receiving script (PHP?) on the server is adding the data someway.
I would suggest you to print the content of parameter with
NSLog(#"param: %#", param);
just to be sure, and also convert the postData to a NSString with something like:
NSString *myString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
and print that too, just to be on the safe side and, once you have make certain that you aren't sending the "token" parameter, start to debug the receiving end.
Hope this helps
It is a magic problem with a NSDictionary. When I send as NSMutableString - no problems.
NSMutableString *stringData = [[NSMutableString alloc] init];
[params enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
[stringData appendString:[NSString stringWithFormat:#"%#=%#", key, value]];
[stringData appendString:[NSString stringWithFormat:#"&"]];
}];
NSData *postData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
I don't know what happens and why :(

ApexRest JSON Parser error when calling Salesforce webservice saying unexpected parameter using through iOS

In calling apexrest webservice for uploading attachment to specific record by calling method. So for this I hardcoded Json.
-(void)uploadToSalesforce
{
NSData *imagedata = UIImageJPEGRepresentation(imagePreview.image, 1.0);
int datalength = [imagedata length];
NSString *filename = [NSString stringWithFormat:#"Supload_iPhone_%d.jpg",datalength];
NSString *req = [NSString stringWithFormat:#"{\n\"name\":\"%#\",\n\"Body\": \"%#\"\n,\"ParenId\":%#\"\n}",filename,imagedata,receivedrecordid];
const char *utfString = [req UTF8String];
NSData *postData = [NSData dataWithBytes:utfString length:strlen(utfString)];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *requestUrl = [[NSMutableURLRequest alloc] init ];
[requestUrl setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/services/apexrest/Account/",receivedinstanceurl]]];
[requestUrl setHTTPMethod:#"POST"];
[requestUrl setValue:postLength forHTTPHeaderField:#"Content-length"];
[requestUrl setValue:[NSString stringWithFormat:#"Bearer %#",receivedaccesstoken] forHTTPHeaderField:#"Authorization"];
[requestUrl setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestUrl setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *reponseData = [NSURLConnection sendSynchronousRequest:requestUrl returningResponse:&response error:&err];
NSString *res = [[NSString alloc] initWithData:reponseData encoding:NSASCIIStringEncoding];
}
In response it says there is
[{"message":"Unexpected parameter encountered during deserialization: Name at [line:2, column:9]","errorCode":"JSON_PARSER_ERROR"}]
In console JSON seems correct but cannot parse parameter "Name".I think this is not by IOS code. Or is there some different format.
In the line
NSString *req = [NSString stringWithFormat:#"{\n\"name\":\"%#\",\n\"Body\": \"%#\"\n,\"ParenId\":%#\"\n}",filename,imagedata,receivedrecordid];
JSON is missing " character for ParentId key value. It should be:
NSString *req = [NSString stringWithFormat:#"{\n\"name\":\"%#\",\n\"Body\": \"%#\"\n,\"ParenId\":\"%#\"\n}",filename,imagedata,receivedrecordid];
Therefore Salesforce webservice deserialization was throwing exception.

Resources