I am creating my first iPad app. I have a web application that I would like to authenticate against and pull data from in a RESTful way.
If you open up the URL in the browser (https://myapp.com/auth/login), you will get a form to enter your username and password. I was thinking I could set the login credentials in the post data of the request and submit the data.
The site uses HTTPS for login so that credentials aren't passed in plain text over the internet.
How can I make a secure HTTPS connection to pass credentials? Will this remember that I am logged in for future requests? What is the best way to do this?
Further update, October 2013
Although at the time I wrote this answer, ASIHTTPRequest was maintained a widely supported, this is no longer the case. It is not recommended for new projects - instead use NSURLConnection directly, or use AFNetworking.
With AFNetworking, there is a [httpClient setAuthorizationHeaderWithUsername:username password:password]; method for http authentication, and create a POST style form is equally easy - see AFNetworking Post Request for that.
Original answer:
A lot of people use the ASIHTTPRequest class to deal with http & https on the iPhone/iPad, as it has a lot of useful features that are difficult or time consuming to achieve with the built in classes:
http://allseeing-i.com/ASIHTTPRequest/
Starting at the simplest level you'd start with something like:
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"response = %#", response);
}
If you're using HTTP authentication, ASIHTTPRequest will automatically prompt the user for the username and password.
IF you're using some other form of authentication you probably need to request the username and password from the user yourself, and submit them as a POST value or a custom http header, and then the response may either include a token in a JSON or XML response, or it could set a cookie.
If you add more details as to how the authentication scheme works I can be a bit more specific.
Update
Based on the update, to emulate a POST form you'd just need to add lines like:
[request addPostValue:usernameString forKey:#"username"];
[request addPostValue:passwordString forKey:#"password"];
You will also need to change the way you create the request, instead of:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
do:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
(I also forget to mention it above, there's code I put earlier is using a synchronous request, so you'd want to replace it with an asynchronous one to avoid blocking the UI once you'd proved it was working.)
There's a JSON framework for the iphone here:
http://code.google.com/p/json-framework/
which works well for me and is simple to use with ASIHTTPRequest.
Related
I am JSON newbie and can't find any material on how to simulate JSON payload request.
My ultimate goal is to be able to build an objective-c iOS app that will handle these request-response. I am aware of ASIHttprequest framework and the request-response mechanism it works around.
However right now I have a webservice api which expects various json payloads and also provides response in json format. Here is an example:
Example URL:
https://mywebServiceURL/api/ApiKey/user/create
The ContentType header = “application/json”.
Payload: The PUT payload is a JSON dictionary, containing the following keyvalue pairs:
email
screenName
User’s screen name.
password
passwordConfirm
phoneNumber (optional)
User’s phone number (optional)
picture A png file (64x64), encoded as a Base64 string (optional)
Now my questions:
1 - how do I simulate this normally (outside ios, just for the sake of testing)? I searched google but can't find exactly what I need, I got curl.exe but it gives me same as what a browser gives, like method not allowed etc. But that's not the only thing I want. I want to play with various requests, supply values and take the api for a ride for sometime before I know how it really works for PUT, GET, POST etc.
2 - what is the best way to incorporate such stuff into iOS? I already have ASIHttp for web requests and JSONKit for JSON handling included in my project.
I have done this kind of stuff but with xml responses, get requests. JSON I am working for the first time. Just a pointer to an example stuff like this would be a great help.
There are several Chrome extensions, such as Advanced REST client or REST Console, that you can use to simulate REST calls. These are very quick and easy to install into your browser and will allow you to construct requests and view the response.
I recommend using the open source iOS networking library AFNetworking. This library has built in support for REST calls and JSON parsing. It is very easy to get up and running, and is very powerful if you need more advanced features.
Hope this helps.
Jsut to add upon Andy's suggestions as I have used similar kind of things in one of my recent app.
Used Chrome extension Poster for testing REST calls.
Used ASIHttpRequest for handling async queries.
Sample code snippet
//dictionaryData contains the login user details
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryData options:kNilOptions error:nil];
NSString *jsonString = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]autorelease];
//Handling ASI requests
ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:uri];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request appendPostData:[jsonData dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[ASIHTTPRequest setDefaultTimeOutSeconds:30];
request.delegate = self;
[request startAsynchronous];
I am wondering what the difference between Get and Post with asihttprequest library..
Is this a GET?
- (IBAction)sendHttpsRequest
{
//Set request address
NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:#"https://142.198.16.35"];
//call ASIHTTP delegates (Used to connect to database)
NSURL *url = [NSURL URLWithString:databaseURL];
//This sets up all other request
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
is a post when you try to set elements say within a php document? any examples would be awesome!
http://www.cs.tut.fi/~jkorpela/forms/methods.html
An HTTP GET is a request from the client to the server, asking for a resource.
An HTTP POST is an upload of data (form information, image data, whatever) from the client to the server.
What you have there is an HTTP POST.
-EDIT:
Per http://allseeing-i.com/ASIHTTPRequest/:
ASIFormDataRequest
A subclass of ASIHTTPRequest that handles x-www-form-urlencoded and multipart/form-data posts. It makes POSTing data and files easy, but you do not need to add this to your project if you want to manage POST data yourself or don’t need to POST data at all.
My bad, this one was a POST, not a GET. The rest of my answer was valid, though :)
That is a POST request, which is the default for ASIFormDataRequest. The difference is the same as it would be in a normal HTTP request. You can read about that here if you don't already know.
In general, if you are just downloading a web page and do not need to send any variables to the server, a GET request is sufficient. If you want to send variables in your request, often times a POST request is the way to go since it is a bit more secure and less transparent.
I am using ASIHTTPRequest in my IOS application to call a wsdl/SOAP web services. my clients use a security mod ( with his ModSecurity / a PHP code).
i am using this :
NSData *xmlData = // I construct the soap message witk soapui
NSURL *url = [NSURL URLWithString:#"https:myUrlWSDL"];
self.currentRequest = [ASIFormDataRequest requestWithURL:url];
[self.currentRequest appendPostData:xmlData];
[self.currentRequest setDelegate:self];
[self.currentRequest startAsynchronous];
But the server send to me the 400 bed request.
How i can, please, do to call my wsdl/web services with all this security mode ? what are the http headers required to call the web services ? thanks for your answers
i have disabled the secure module. now i have this error :
WSDLSOAP-ERROR: Parsing WSDL: Couldn't load from 'http://...?wsdl' : failed to load external entity "http://...?wsdl"
That's how you use ASI to call a secure connection - you're doing everything correctly.
The problem must be in your code that creates the xmlData - what other error information can you get back from your clients server?
You might also need to add more headers to the request (though thats also something that your clients should be able to tell you) - e.g.
[request addRequestHeader:#"Referer" value:#"http://allseeing-i.com/"];
I need to login here. I've tried the ASIHTTPRequest and ASIFormDataRequest.
None of them works as expected. I only got the data from the loginpage in the response string, not the data from the secure area.
What am I doing wrong here?
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"https://www.blau.de/"]];
[request setPostValue:#"USERNAME" forKey:#"quickLoginNumber"];
[request setPostValue:#"PASSWORD" forKey:#"quickLoginPassword"];
[request startAsynchronous];
There are a couple of good tools you can use to try to debug this. In all likelihood there is a 302 redirect after logging in. You can watch for that (among other conditions) using tools such as:
HTTPScoop (worth the $15 bux): http://www.tuffcode.com/
Live Headers (a free FireFox plugin): https://addons.mozilla.org/en-US/firefox/addon/3829/
Keep in mind that what you're trying to do is not simple. I've gotten it to work with some sites, but not others and the reasons for one or the other can be quite elusive.
Hi I am currently designing my second iphone app, and having a small issue.
I have the location code working correctly but I have no idea how to send the label with the location info to my server.
I was wondering and hoping someone might be able to help.
Thanks
Russell
That would depend entirely on what your PHP script expects to receive. Your most obvious choices would be to put the coordinates in the query string or in a POST request.
Use ASIHTTPRequest for http requests. http://allseeing-i.com/ASIHTTPRequest/
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Josh" forKey:#"first_name"];
[request setPostValue:#"Highland" forKey:#"last_name"];
[request start];