Sending information to server using URLs - iphone

I'm currently working with a PHP developer to set up some server-side code, however, I'm not sure how to send the server API information to be stored in a database. He has asked me to send it in a url like this: exampleserver.com/register?deviceToken=[deviceToken]&otherstuff[otherStuff]. I have no problem with creating the URL string, my issue is actually doing something with it. I know this is a pretty stupid question, but I'm pretty new to Objective-C let alone communicating with servers! I have pulled information from servers using NSURLRequest and AFJSONRequestOperation before. Is it the same idea or are we no longer doing Requests? I've seen the word Post around a couple of times, but I'm unsure if this is what I'm after. Any help clearing this up would be really appreciated. Also, whatever the solution, I need it to be asynchronous!
Thanks for the help,
Regards,
Mike

This works for me:
NSURL *aURL = [NSURL URLWithString:#"http://www.google.co.uk/search?hl=en&q=hello%20world"];
NSURLRequest *aURLRequest = [NSURLRequest requestWithURL:aURL];
[NSURLConnection sendAsynchronousRequest:aURLRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
NSLog(#"response=%#", response);
NSLog(#"data=%#", data);
NSLog(#"error=%#", error);
}];
The URL you show has data tacked onto the end of the URL, which is normally done with a http GET operation, the "normal" method. Just asking for the page at that URL is enough to send the data to the server. An http POST operation is typically used to send form data to a server, where the pairs like deviceToken=<deviceToken> are transferred in the body of the message rather than the URL. The advantage of that is typically that the body will be encrypted if the connection is https:, so the data stays secure. But for a simple insecure transaction, using a GET with the parameters in the URL is fine. There's a description of a POST transaction at iOS: how to perform a HTTP POST request?

NSURLRequest still works and is fine. If you want a more powerful library that handles post, get, put etc. and can work asynchronously and link directly to core data, I recommend RestKit (https://github.com/RestKit/RestKit).
For more on NSURL, see my answer here: NSURLConnection delegate method

Related

How to initiate webservice request that expects JSON payload

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];

Sending data to a website and getting results of search iOS

I am very new to iOS and I've just begun reading about HTTP requests and POST and GET methods. Let's say, for example, I want to have the user input a string, and then send that data to a website, (for this example, say www.rhymezone.com), search with that string, and get the results of that search within my application. Is this done with an HTTP post method? Or what? Any help / examples would be greatly appreciated. Also, if there are tutorials for this stuff, that would be appreciated as well.
For sake of example, here is what I've tried:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.rhymezone.com/r/rhyme.cgi?Word=test&typeofrhyme=perfect&org1=syl&org2=l&org3=y"]];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *dataAsString=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data: %#",dataAsString);
}
This outputs the entire source of the website (searching for rhymes of the word test). While I can certainly write a method to go through the source of the website and extract the words it returns, I feel like this is not correct. My way of getting rhymes of different words is simply to change the URL here, so where it says 'test' I change it to whatever the user inputs.
Thanks
Look into AFNetworking and RestKit.
It's easiest if you're calling a public API that uses JSON/XML, and then use a built in parser or a parser library to extract the data you want.
Simply downloading the contents of a URL is an HTTP GET request, such as going to a website.
This link talks a bit more about the difference between GET and POST.
When do you use POST and when do you use GET?
If I understand correctly what you are trying to do, I fear that the only option for you is sending the HTTP request (GET or POST according to what the website expects, just like you are doing) and then parse the result to filter all the information that is not relevant.
An alternative approach would be possible if you were using a website offering a REST API, or a JSON API so that you send the query and you get back just the information you need (in a specific format).
So, it depends strongly on the website you are using, but for the generic case, the only option you have is parsing.
(Or, you could display the full content of the page through UIWebView. This would not require explicitly setting up a connection, but I am not sure it is what you are trying to do.)
You are looking for a way to communicate with your website from your iOS application. The common approach is to get the string entered by the user, encode and send it as http request to a sort of script (webservice). This script will do all the stuff you want (search with this string). Then re-send the result to the client (your iOS app) as a http response which will be parsed in your iOS app(with a JSON parser for instance).
There is good resources around that, as an example, you may read this: http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service

Retrieving response from a php url in iphone

I have created an api. Lets say this is my php url
"http://xxxxxxx/game/game.php?validate=yes&email=myEmail#mars.com"
The response of this query is either 1 0r 0. It validates the email if it exists in db or not. I have been searching but failing till now, How am i suppose to send it to server. By NS URL or I have to use NSURLConnection. How in turn I can read the response.
Best Regards
NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://xxxxxxx/game/game.php?validate=yes&email=myEmail#mars.com"]];
Bible, Old Testament.
Bible, New Testament.
Edit: so the response is XML? Right. (No, not right, you should really consider using JSON, but anyways...) You can use the NSXMLParserClass to get back the response in this case. Especially have a look at its - initWithContentsOfURL: method.

iOS NSURLConnection object always returns same response

I'm creating an iPhone app that consumes a json webservice. I have an NSURLRequest and NSURLConnection object that are used to load JSON data from that webservice:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:30];
[request setHTTPMethod: #"POST"];
//[request setHTTPShouldHandleCookies:YES];
//create connection
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request delegate:self];
[connection start];
First time I executed the above code, using as the url "admin.mydomain.com/param1/value1/param2/value2", the response came through correctly (a JSON string: {"Wrong API Key"}).
I then changed the url to my staging server: "admin.stg.mydomain.com/param1/value1/param2/value2". This server provides me with some completely different output (when I try that new url in a browser, the correct output is shown, a json object completely different from what the first url gives me), but in my iphone app I still get the exact same response I got from the other server. If I try non existent urls I do get a correct error message.
It just seems to have cached the result from the original server and returns the same value for my stg subdomain, somehow matching the two urls (is this possible?), but I have cleared all caching data I could find. I have tried to clean the build and build directory, restarted xcode, the computer and everything, the cache policy is set to ignore the cache (see code). Important: I get the same behavior on my actual iPhone, not just the simulator.
Does anyone have any idea what could cause this kind of behavior? Am I forgetting something obvious?
I have been looking at this for hours on end now, any help is greatly appreciated!
I have changed the request method to 'GET', now I get the expected results! When checking the url in the browser a get request is used, when posting it I get a different response, which happens to be exactly the same as what I get on the dev server. Problem solved, just have to make some adjustments to the backend to allow a post request!

what is the difference between post and get request for asihttprequest?

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.