JSON POST Request on the iPhone (Using HTTPS) - iphone

I have a WCF service hosted and I'm trying to use it within an iPhone app as a JSON POST request. I plan on using the JSON serializer later, but this is what I have for the request:
NSString *jsonRequest = #"{\"username\":\"user\",\"password\":\"letmein\"}";
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://mydomain.com/Method/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
In my data received I'm just printing it to the console:
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSMutableData *d = [[NSMutableData data] retain];
[d appendData:data];
NSString *a = [[NSString alloc] initWithData:d encoding:NSASCIIStringEncoding];
NSLog(#"Data: %#", a);
}
And within this response I get this message:
Data: <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Request Error</title>
<style>
<!-- I've took this out as there's lots of it and it's not relevant! -->
</style>
</head>
<body>
<div id="content">
<p class="heading1">Request Error</p>
<p xmlns="">The server encountered an error processing the request. Please see the <a rel="help-page" href="https://mydomain.com/Method/help">service help page</a> for constructing valid requests to the service.</p>
</div>
</body>
</html>
Does anyone know why this happens and where I'm going wrong?
I've read about using ASIHTTPPost instead but I can't get the demo to run in iOS4 :(
Thanks
EDIT:
I've just used to CharlesProxy to sniff out what's happening when I call from the iPhone (Simulator) and this is what it gave me:
The only thing strange I've noticed is it says "SSL Proxying not enabled for this host: enable in Proxy Settings, SSL locations". Does anyone know what this means? (This also happens in my working windows client).
I've just ran this on my windows client and the only thing that is different is the Request and Response text which is encrypted. Am I missing something in order to use a secure HTTP connection to do this?
NEW EDIT:
This works with a non-HTTPS request such as:
http://maps.googleapis.com/maps/api/geocode/json?address=UK&sensor=true. So I guess the problem is getting the iPhone to send the POST properly over SSL?
I am also using these methods:
- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void) connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
{
return YES;
}
}
This allows me to get this far. If I don't use them I get an error sent back saying:
The certificate for this server is invalid. You might be connecting to a server that is pretending to be “mydomain.com” which could put your confidential information at risk.

FIXED!
Changed:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
to:
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
You also need these two methods:
- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void) connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
{
return YES;
}
}

I don't know Objective C at all, but try setting the Accept header to application/json instead of application/jsonrequest.

change
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
to
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

dic is NSMutable Dictionary with object and keys.
baseUrl is your server webservice url.
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *encodedString = [jsonString base64EncodedString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#wsName",baseUrl]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:encodedString forHTTPHeaderField:#"Data"];

Related

JSON Webservice issue in iPhone?

Currently i am working in iPhone application, Using JSON to send a request and get response to read it.
Request (example url):
http://www.Genifer.com/index.php?q=api/username-available&username=stephen
I refer the Response from browser (Firefox):
{"status":true,"result":true}
I tried in xcode:
NSString *urlString = [NSString stringWithFormat:#" http://www.Genifer.com/index.php?"];
NSString *parameter = [NSString stringWithFormat:#"q=api/username-available&username=stephen"];
NSData *parameterData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:parameterData];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if( connection )
{
mutableData = [[NSMutableData alloc] init];
}
else
{
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutableData setLength:0];
NSLog(#"mutableData:%#",mutableData);
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
NSLog(#"mutableData:%#",mutableData);
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[mutableData release];
[connection release];
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonStr = [[NSString alloc] initWithData:mutableData encoding:NSUTF8StringEncoding];
NSLog(#"JSonSTr : %#", jsonStr);
}
Response comes:
JSonSTr : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
i refer the request in Firefox browser get the response like {"status":true,"result":true}.
But i tried to integrate same request in xcode, but the response comes different, How to fix this?
Please help me
Thanks in Advance
Can you check with this
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
Check what values pop up in your dictionary by doing something like this
NSDictionary *question = [jsonDict objectForKey:#"status"];

iOS Forms Authentication

I need to:
1) Authenticate against a forms authentication service
2) Save off cookie
3) Call web service with cookie
And I'm having a hell of a time trying to get this working. Has anyone had any luck with this? It seems like a very common operation.
Here's my code:
Hit auth URL and get the cookie:
- (IBAction)buttonGetCookieTap:(id)sender {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.cookieURL];
[request setHTTPShouldHandleCookies:YES];
[request setHTTPMethod:#"POST"];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- ( void )connection: (NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response
{
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSDictionary *fields = [HTTPResponse allHeaderFields];
self.cookie = [fields valueForKey:#"Set-Cookie"];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:#"blah"
password:#"blah"
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
Now call auth service with the cookie:
- (IBAction)buttonCallServiceTap:(id)sender {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.dataURL];
[request addValue:self.cookie forHTTPHeaderField:#"Cookie"];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
Edit: Sorry, the problem I have is that I'm getting a barebones cookie back with just the session id but on the server end the cookie looks fine. Can anyone verify that there's nothing wrong with my cookie grabbing code? I've tried many variations of this and have the same problem. Thanks!
I wrote an answer to a Stack Overflow question here, which provides sample code for examining your application's cookies. Someone else in that thread provided additional code for getting app-side cookie details. You might start there, to help troubleshoot authentication.
I figured out how to do this, I had to build a soap message for the HTTP Body.
NSString *soapFormat = [NSString stringWithFormat:#"<?xml version='1.0' encoding='UTF-8'?>\n"
"<soap:Envelope\n"
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n"
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
"<soap:Body>\n"
"<Login xmlns=\"http://asp.net/ApplicationServices/v200\">\n"
"<username>myusername</username>\n"
"<password>mypassword</password>\n"
"</Login>\n"
"</soap:Body>\n"
"</soap:Envelope>\n"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:self.authURL];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"http://asp.net/ApplicationServices/v200/AuthenticationService/Login" forHTTPHeaderField:#"SOAPAction"];
[request addValue:[NSString stringWithFormat:#"%d",[soapFormat length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[soapFormat dataUsingEncoding:NSUTF8StringEncoding]];
self.authConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
I can grab the cookie from didReceiveResponse
- ( void )connection: (NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response
{
if (self.currentCookies == nil) {
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
self.currentCookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[HTTPResponse allHeaderFields] forURL:[NSURL URLWithString:#""]];
NSLog(#"COOKIE: %#",((NSHTTPCookie*)[self.currentCookies objectAtIndex:1]).value);
}
}
Then I use the cookie to get JSON data from the webservice.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.dataURL];
[request setHTTPMethod: #"GET"];
NSString *cook = [NSString stringWithFormat:#".ASPXAUTH=%#",((NSHTTPCookie*)[self.currentCookies objectAtIndex:1]).value];
[request addValue:cook forHTTPHeaderField:#"Cookie"];
[request setHTTPShouldHandleCookies:NO];
self.dataConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I hope this helps someone who has a similar authentication system.

iPhone authentication process

I have trouble finding info on this topic. Please help me out here.
I need to pass arguments via POST or GET method to my web server and get a reply.
Basically, if using GET method, I want to do something like server.com/?user=john&password=smith and receive the dynamically generated HTML code that is done with my php script. All this without using the web browser on my app.
How is it usually done?
You'll want to look into NSMutableURLRequest and NSURLConnection.
For example, you could use them like this do to a GET request to your server:
- (void)loginUser:(NSString *)username withPassword:(NSString *)password {
// GET
NSString *serverURL = [NSString stringWithFormat:#"http://yourserver.com/login.php?user=%#&pass=%#", username, password];
NSURL *url = [NSURL URLWithString:serverURL];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:req delegate:self];
if (connection) {
connectionData = [[NSMutableData alloc] init];
}
}
This will send an asynchronous GET request to your server with the query string containing username and password.
If you want to send username and password using a POST request, the method would look something like this:
- (void)loginUser:(NSString *)username withPassword:(NSString *)password {
// POST
NSString *myRequestString = [NSString stringWithFormat:#"user=%#&pass=%#",username,password];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSURL *url = [NSURL URLWithString:#"http://yourserver.com/login.php"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod: #"POST"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[req setHTTPBody: myRequestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:req delegate:self];
if (connection) {
connectionData = [[NSMutableData alloc] init];
}
}
In order to get the response from the server, you will need to implement the NSURLConnection delegate methods, for example:
#pragma mark -
#pragma mark NSURLConnection delegate methods
#pragma mark -
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
// Called if you have an .htaccess auth. on server
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:#"your_username" password:#"your_password" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[connectionData setLength: 0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[connectionData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connectionData release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *content = [[NSString alloc] initWithBytes:[connectionData bytes]
length:[connectionData length] encoding: NSUTF8StringEncoding];
// This will be your server's HTML response
NSLog(#"response: %#",content);
[content release];
[connectionData release];
}
References:
NSMutableURLRequest Class Reference
NSURLConnection Class Reference
Hope this helps :)
Usually this is done using a NSURLConnection. You can also use NSString's method stringWithContentsOfURL.

How to post and get asmx web serivce access using iPhone app?

I am new to iPhone app development. How can I post data and get data by accessing the asmx web service using iPhone app?
I think asmx webservices are SOAP webservices you should read my blog entry here -
http://www.makebetterthings.com/iphone/call-soap-web-service-from-iphone/
To call a SOAP service first i create a string with the SOAP request as follows.
NSString *soapMessage = #"<?xml version="1.0" encoding="utf-8"?>n"
"<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">n"
"<soap:Body>n"
"<CelsiusToFahrenheit xmlns="http://tempuri.org/">n"
"<Celsius>50</Celsius>n"
"</CelsiusToFahrenheit>n"
"</soap:Body>n"
"</soap:Envelope>n";
After creating the SOAP request I create a NSMutableRequest to send this request to server.
NSURL *url = [NSURL URLWithString:#"http://w3schools.com/webservices/tempconvert.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/CelsiusToFahrenheit" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
After firing the request we can collect the XML response in the NSURLConnection’s delegate methods.
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",theXML);
[theXML release];
}
After collecting the XML response in theXML string in -(void)connectionDidFinishLoading:(NSURLConnection *)connection
we can parse this string using TBXML for any other XML parser you like.

Basic HTTP Authentication on iPhone

I'm trying to get a small twitter client running and I ran into a problem when testing API calls that require authentication.
My password has special characters in it, so when I try to use the following code it doesn't work.
NSString *post = [NSString stringWithFormat:#"status=%#", [status stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#:%##%#/statuses/update.json", username, password, TwitterHostname]];
[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];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I started looking into base64 and putting the authentication into the headers. I found Dave Dribin's post on his base64 implementation, and it seemed to make sense. However when I tried to use it the compiler started complaining about how it couldn't find the openssl libraries. So I read that I needed to link in the libcrypto library, but it doesn't seem to exist for iphone.
I've also read people saying that apple won't allow apps that use crypto libraries, which doesn't make sense to me.
So now I'm kinda stuck and confused. What's the easiest way to get basic authentication into my app?
Cheers
Two things. Firstly you have to use the async methods rather than the synchronous/class method.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:req]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
The authentication is managed by implementing this method in your delegate:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
And you'll probably also need to implement these methods too:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
Using the async method tends to give a better user experience anyway so despite the extra complexity is worth doing even without the ability to do authentication.
You can directly aslo write download the username & password in main URL i.e https://username:password#yoururl.com/
First of all you need to call NSURLConnection Delegate file:-
(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return YES;
}
and then call
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge previousFailureCount] == 0)
{
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:#"username"
password:#"password"
persistence:NSURLCredentialPersistenceForSession];
NSLog(#"NEwCred:- %# %#", newCredential, newCredential);
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
else
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
NSLog (#"failed authentication");
}
}