How to do authenticated service call - ios

Hi I am trying to connect to some server which will use username and password as credentials..Following is the code I am using.
NSString post =[[NSString alloc] initWithFormat:#"userName=*&password=*"];
NSURL url=[NSURL URLWithString:#"******"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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];
NSLog(#"request:%#",request);
urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Here the problem is server is giving user invalid message.But the credentials which i am giving is fine.This username and password is not going in request object..can any one of you please help me..

You need to start with a string that holds your username & password. This will form the http POST body. You need to replace username_input_field & password_input_field with the correct input field names for the webserver. My advice is to use Firefox along with the httpFox extension to login to your webserver. httpFox will show you all the input field names for the request. There may also be extra hidden fields which you'll need to add too.
NSString *post = [NSString stringWithFormat:
#"username_input_field=%#&password_input_field=%#",username,password];

Add the username to the request header object, like so:
[request addValue:#"<username>" forKey:#"<username parameter>"]

Related

How to properly encode UTF-8 in iOS using NSMutableURLRequest?

I am trying to send information to a login web service but certain characters are giving me trouble.
For example, if the password is something like h+4hfP, the web service rejects it because the plus sign ('+') is not properly encoded to %2B.
The web service uses UTF-8 encoding so I have been building an NSData object with this NSString method, - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding; choosing NSUTF8StringEncoding as the encoding.
This doesn't seem to be enough though.
The problem could also be with how I'm building an NSMutableURLRequest:
NSData *postData = [#"h+4hfP" dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
How can I ensure the encoding is done properly?
Use
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
You could percent encode the string before representing it as NSData:
NSString *password = [#"h+4hfP" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
NSData *postData = [password dataUsingEncoding:NSUTF8StringEncoding];
...
This can be a solution:
I was facing this problem. After some hours and search, I discovered this:
http://madebymany.com/blog/url-encoding-an-nsstring-on-ios
Solution:
1st: You must create a method or class with content:
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding withString:(NSString *) str{
return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)str,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding)));
}
2nd: Use:
NSString *stringToSend = [self urlEncodeUsingEncoding:NSUTF8StringEncoding withString:stringToBeVerifyed];
Then
NSData *postData = [stringToSend dataUsingEncoding:NSUTF8StringEncoding];
[...]

Not able to figure out why data posted twice to a api in iOS?

I'm building an iOS app and posting a data to api. I'm facing a problem that i posted a once
but it is reflected twice on the server.And i have checked from rest clients that there is no error at the server side.
here is my code
- (void) next: (UIButton*) sender
{
NSString *post =[NSString stringWithFormat:#"? &sportsname=%#&time=%#&venue=%#&date=%#&players=%#&addinfo=%#&userid=%#&gender=%#&recurring=%#",_selectedSport,_selectedTime,location,dateValue,max,info,UserId,_selectedGender,_selectedRecurring];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://yy.4.yyy.hh:iyiy/api/user/%#/host",UserId]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[self performSegueWithIdentifier:#"hostSubmit" sender:nil];
if(conn)
{
NSLog(#"Connection successfull");
}
else
{
NSLog(#"connection could not be made");
}
}
It's pretty easy to link the same action twice in a button. Look at the actions tab in interface builder and make sure you haven't linked your button to your next: action twice.
Failing that, add a log statement at the beginning of the method "entering method 'next:'" and see if you see the log twice. If you do, go figure out why.

How to post a password with a & symbol

I am trying to create an app that sends a password through POST to a php website, but I am having trouble with the PostData. When the password contains a & symbol it thinks that the variable will be split into two.
For example:
Username: testuser
Email: email#email.com
Password: Pass&word1
The following would be the PostData
username=testuser&email=email#email.com&password=Pass&word1
^This breaks the password up
This is my code:
#try {
NSString *post = [[NSString alloc] initWithFormat:#"username=%#&email=%#&password=%#", usernameField.text, emailField.text, password1Field.text];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://mywebsite.com/test/register.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
}
#catch (NSException *exception) {
NSLog(#"Exception: %#", exception);
}
EDIT
I also just realized that letters like: àìú are causing problems as well.
Ampersands have special meaning in HTTP requests. You'll need to URL encode those parameters to make sure that the server software knows that they are data.
You'll need to do something like this for each parameter in the request string:
NSString* encodedPassword = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)password1Field.text,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(NSUTF8Encoding));
Take a look at this reference for a great example of adding your URL encoder to the NSString class: http://madebymany.com/blog/url-encoding-an-nsstring-on-ios
As for your edit, characters like àìú are probably giving you problems because you are using NSASCIIStringEncoding. Try NSUTF8StringEncoding as it supports a much larger range of potential characters than ASCII.
Simple solution: Use '|' instead of '&' in your Objective C code.

POST request on iOS - not working

I have an iOS application which connects via OAuth 2.0 to Facebook. I would like to make a POST request which achieves the equivalent of this code in iOS:
curl -F 'access_token=...' \
-F 'message=Hello. I like this new API.' \
https://graph.facebook.com/[USER_ID]/feed
I found a nice tutorial online and I followed all the instructions, but I still can get my POST request to work. Here is my code:
NSString *post = post_text.text;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *ready_post = [NSString stringWithFormat:#"https://graph.facebook.com/1313573269/feed?message=%#&access_token=CAACEdEose0cBAHgdZAon2EZBZCzjoLkhg7jrqvZAbliuoOQ2E2Exc4rZCAxPzeVEADwnQaNLYuG16Gq6q6LLLLLLLLVQ7LZAncXCc53qE2iyzleZAPXGajsgjnBTuo6YdJCZAxVGIYYD8sZCgQ9ypZCo0iOZBNuyrechBfee2yptlK9tmgdosZA7wrKg8ZD", postData];
[request setURL:[NSURL URLWithString:ready_post]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
As you can see I am hard coding the access token for the time being just as a test. But I cant seem to get my app to actually POST anything to Facebook.
Thanks, Dan.
You're trying to post a JSON to the GraphAPI - which you can't do.
Instead of that, you have to use parameters when posting (query string or HTTP request parameters).
See: Publish to Feed.

Calling asp.net web service from iOS application crash when data contains ampersands?

I have an application which actually calling asp.net web service but when I transfer data with & it stop working. Like below jsonString have first_name which have "Pranav &" so as this stage when I call service with converting it in asciistringencoding it generate error because of ascii convert it like
&quotPranav &&quot
with finding two ampersands it stop working
NSString * jsonString = #"{"home_phone":"123","GroupId":"GP00000099","first_name":"Pranav &","city":"df","last_name":"Purohit","state":"sl","email":"pjp#gmail.com","member_Id":"GM00008513"}";
NSString * post = [[NSString alloc] initWithFormat:#"jsonText=%#", jsonString];
NSLog(#"%#",post);
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.myweburl.com/mywebservice.asmx/mymethod"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I got answer, when you embed & replace it with \u0026

Resources