Pass username and password in URL for authentication - iphone

I want ot pass username and password in URL(web service) for user authentication which will return true and false.I'm doing this as following:
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://URL/service1.asmx"]];
[request setHTTPMethod:#"GET"];
Now, I wanted to know How can I pass my username and password in this URL to make request.
Could any one please suggest or give some sample code?
Thanks.

Try this :-
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName.text];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword.text];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord]]];
[request setHTTPMethod:#"GET"];
Hope it helps you..

NSString *urlStr = [NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord];
[request setURL:[NSURL URLWithString:urlStr]];

To improve the secure , you may use the Http Basic Authentication.
There are answer here.

First off I would not pass a username and password across in a url. You should do this using post.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?"]];
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSString *postString = [NSString stringWithFormat:#"username=%#&password=%#",userName, passWord];
NSData *postData = [NSData dataWithBytes: [postString UTF8String] length: [postString length]];
//URL Requst Object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:TIMEOUT];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postData];
This is more secure then passing sensitive data across in a url.
Edit
To get the response you can check this out. NSURLConnection and AppleDoc NSURLConnection
You can use a few different methods to handle the response from the server.
You can use NSURLConnectionDelegate
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
along with the delegate call backs:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData");
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}
Or you can also use NSURLConnection sendAsynchronousRequest block
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}];

Related

posting data to server from iphone app

I am posting data to server from iphone app but it gives exception while reading post line code about "excess bad access".Same code I use for sending four variables data then it is working fine if i add more variables in post it gives an error.
NSString*category=titleCategory;
NSString*sub_Category=titleSubCategory;
NSString*content_Type=#"Audio";
content_Title=TitleTextField.text;
NSString*content_Title=content_Title;
NSString*publisher=#"Celeritas";
content_Description=descriptionTextField.text;
NSString*content_Description=content_Description;
NSString*content_ID=#"10";
NSString*content_Source=#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/productivo/pro/ali.wav";
NSString *post =[[NSString alloc] initWithFormat:#"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#",category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];
NSURL *url=[NSURL URLWithString:#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/addData.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
Below is the line where it breaks the code
NSString *post =[[NSString alloc] initWithFormat:#"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#",category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];
Try this
NSString *args = #"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#";
NSString *values=[NSString stringWithFormat:args,category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];
NSData *postData = [values dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *path = [[NSString alloc] initWithFormat:#"%s",your urlpath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:path]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[values dataUsingEncoding:NSISOLatin1StringEncoding]];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&err];
NSString *returnString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[NSURLConnection connectionWithRequest:request delegate:self];
//NSLog(#"String==> %#",returnString);
Hope this helps...
Good luck !!
Following code a help a lot while i test into the project as well as
In .h File
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController{
NSURLConnection *connection;
NSMutableData *responseData;
}
#end
In.m File
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString*category=#"Cat1";
NSString*sub_Category=#"Title";
NSString*content_Type=#"Audio";
NSString* content_Title=#"Test";
NSString*publisher=#"Celeritas";
NSString*content_Description=#"Content Description";
NSString*content_ID=#"10";
NSString*content_Source=#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/productivo/pro/ali.wav";
NSString*post = [NSString stringWithFormat:#"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#",category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];
NSURL *url=[NSURL URLWithString:#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/addData.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if(connection){
responseData=[NSMutableData data];
}
}
#pragma NSUrlConnection Delegate Methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// [delegate APIResponseArrived:NULL];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString =[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// [delegate APIResponseArrived:responseString ];
NSLog(#"%#",responseString);
}
This code solve your problem.
I got the solution of the question actually there was variable assignment issue for their invailded address that is why it was giving access bad error i assigned values directly then it worked for me fine like
NSString*category=#"Category";
NSString*sub_Category=#"Working";
NSString*content_Type=#"Audio";
NSString*content_Title=#"Content Title";
NSString*publisher=#"Celeritas";
NSString*content_Description=#"ContentDescription";
NSString*content_ID=#"10";
NSString*content_Source=#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/productivo/pro/ali.wav";
NSString *post =[[NSString alloc] init];
post = [NSString stringWithFormat:#"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#",category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];
NSURL *url=[NSURL URLWithString:#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/addData.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];

Add new place to Google Places

I am new to IOS. I have to add new places to Google Places. I have referred this link https://developers.google.com/places/documentation/actions to add a place on button click, but I'm confused about passing parameters for this.
My coding lines are like this to fetch:
NSString *lat =#"-33.8669710";
NSString *longt =#"151.1957362";
gKey = #"my api key";
NSString *placeString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key=%#HTTP/1.1Host:maps.googleapis.com {\"location\":{\"lat\":%#,\"lng\":%#},\"accuracy\": 50,\"name\":\"Gimmy Pet Store!\",\"types\":[\"pet_store\"],\"language\":\"en-AU\"}",gKey,lat,longt];
placeString = [placeString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Main Place Url: %#",placeString);
NSURL *placeURL = [NSURL URLWithString:placeString];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:placeURL];
[request setHTTPMethod:#"POST"];
NSURLConnection *placesConn =[[NSURLConnection alloc] initWithRequest:request delegate:self];
I have made following changes to my code & finally it is executed successfully...
//for setting Parameters to post the url.just change tag values to below line...
NSString *str1 = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><PlaceAddRequest><location><lat>your latitude</lat><lng>your longitude</lng></location><accuracy>50</accuracy><name>place name</name><type>supported type</type><language>en-US</language></PlaceAddRequest>"];
NSLog(#"str1=====%#",str1);
NSString *str2 = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *requestdata = [NSData dataWithBytes:[str2 UTF8String] length:[str2 length]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestdata length]];
//requesting main url to add new place to google places
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/add/xml?sensor=false&key=your api key"]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:[str1 UTF8String] length:[str1 length]]];
//NSURLConnection *placesConn =[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *returndata = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnstr = [[[NSString alloc] initWithData:returndata encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"returnstr: %#",returnstr);
& then i have decoded return response which i get i status as OK......:)
Any one can use above code...if any help require you can surely ask....:)

newby IOS: unable to redirect url

This is my first IOS project. Having a tough time getting login to work. The site has a meta_refresh to another url. I've tried to send another request to the url in the meta_refresh but then the app just hangs. I'm sure that I'm doing something wrong but I'm using XCode 4.4 so a lot of the NSURLConnection delegate methods have been deprecated.
Here's what I'm doing:
NSString *urlAsString = baseURL;
urlAsString = [urlAsString stringByAppendingString:#"?user[login]=username"];
urlAsString = [urlAsString stringByAppendingString:#"&user[password]=password"];
urlAsString = [urlAsString stringByAppendingString:#"&origin=splash"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"POST"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if([data length] > 0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
NSRange obj = [html rangeOfString:#"http-equiv=\"refresh\""];
NSInteger len = obj.length;
} else if([data length] == 0 && error == nil) {
NSLog(#"No data was returned.");
} else {
NSLog(#"Error happened = %#", error);
}
Here's what I'm getting:
Another question is that I've read that I should use asynchronous connection. The trouble is that I need the data scraped from the site to display on the screen. If I display the screen before the data is returned, then I won't have any data -- or am I not understanding how this works?
Thanks.
--Tony
I think that maybe you're a mixing stuff. You're setting a string url with GET values and then you set the HTTPMethod to POST and I don't know if that is going to work fine.
Here's a code that I have to send values with POST:
NSString *post = [NSString stringWithFormat:#"&user_login=%#&user_password=%#&origin=%#,username,password, splash];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:baseURL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

URL Decoding of json in ios

I am having 1 webservice in php which is having browser url mentioned bel :
http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01 01:00:00
Now when I try to fetch url in my iphone app, it is taking this url:
http://Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00
This is creating problem.
i have used this code for fetching data from my url.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"";
NSString *str;
str = #"LastUpdated";
NSString *requestString = [NSString stringWithFormat:#"{\"LastUpdated\":\"%#\"}",str];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
//urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ACTEC"
message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
......
}
here,i am getting null response as url is getting decoded...How can I make this solved...
Help me out.
Thanks in advance.
NSString *urlLoc = [[fileContents objectForKey:#"URL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postData = [NSMutableData data];
NSMutableURLRequest *urlRequest;
[postData appendData: [[NSString stringWithFormat: #"add your data which you want to send"] dataUsingEncoding: NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:urlLoc]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSString *temp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"\n\nurl =%# \n posted data =>%#",urlLoc, temp);
check nslog. that which data u send to service.
NSData *response = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"json_string >> %#",json_string);
Maybe this will help you.
hey dear just for an another example i just post my this code..
first Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
    [NSURL URLWithString:#"http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00"]];
Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request
    returningResponse:nil error:nil];
Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc]
    initWithData:response encoding:NSUTF8StringEncoding];
Parse the JSON response into an object Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil]
And in statuses array you have all the data you need.
i hope this help you...
:)

converting image to base64 and uploading in JSON format to server

I have a problem. I need to convert base64 string to JSON string and pass it to server.
for example I have a base64 string /9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/Z
i need to convert it to JSON format. I do the following:
+(NSData *)prepareForUploading:(NSString *)base64Str
{
NSDictionary *dict=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:base64str, nil] forKeys:[NSArray arrayWithObjects:#"picture", nil]];
NSData *preparedData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
return preparedData;
};
here how I'm making NSURLRequest
-(NSString *)uploadPict:(NSString *)pict
{
NSLog(#"Server: upload: called");
NSData *prepPictData=[[self class] prepareForUploading:pict];
NSString *preparedBase64StrInJSON=[[NSString alloc] initWithData:prepPictData encoding:NSUTF8StringEncoding];
//here I'm adding access token to request
NSString *post = [NSString stringWithFormat:#"accessToken=%#&object=%#", self.key, preparedBase64StrInJSON];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#upload.aspx", serverAPIPath]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"postLength" forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//....
}
But I get "Invalid length for a Base-64 char array" from server. What's wrong?
If I paste my token and JSON to http://hurl.it/ and make request using it - everything goes normally.
I think the problem is / symbols in base64 string and as a result / symbols in JSON.
Maybe it is something with [postData length]: if I erase \/ characters from JSON string:
9j4AAQSkZJRgABAQAAAQABAAD4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQHZ request will perform normally but this base64 encoded string is not the same.
Please, help me to solve this problem
jString is your base64 string, first use following line
[self encodeString:jString];
and then call use following.
NSString *URL = [NSString stringWithFormat:#"forms.asmx/CreateUpdate?"];
URL=[NSString stringWithFormat:#"%#%#", USERS_API_ROOT_URL, URL];
NSString *post = [NSString stringWithFormat:#"apiKey=A0B1I2L3A4L5-A1D3-4F30-5AB2-C8DEE266&strPost=%#",jString];
unsigned long long postLength = [post length];
NSString *contentLength = [NSString stringWithFormat:#"%llu",postLength];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData ];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(NSString *)encodeString:(NSString *)string
{
NSString *newString = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL,CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
return newString;
}
Hope it will work.