I want to connect to a server using HTTP, send a string to it and recieve the response string from the server. Any ideas about how to connect to server by the url, send and recieve message from it?
// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData that will hold
// the received data
// receivedData is declared as a method instance elsewhere
receivedData=[[NSMutableData data] retain];
} else {
// inform the user that the download could not be made
}
See this resource.
I suggest using the excellent ASIHTTPRequest source from All-Seeing Interactive: http://allseeing-i.com/ASIHTTPRequest. I'm doing this, and so are several released iPhone apps, so you can be sure the code is pretty solid.
This is a wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier. It is written in Objective-C and works in both Mac OS X and iPhone applications.
It is suitable for performing basic HTTP requests and interacting with REST-based services (GET / POST / PUT / DELETE). The ASIFormDataRequest subclass makes it easy to submit POST data and files using multipart/form-data.
You can connect to a server, send a string, and receive the response using the NSMutableURLRequest and NSURLConnection classes. A good place to start is the Introduction to the URL Loading System.
Related
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
In my iOS app, I'm using a UIWebView and a custom protocol (with my own NSURLProtocol implementation). I've been fairly careful about making sure that whenever I load a url, I load something like this into my UIWebView:
myprotocol://myserver/mypath
and in my NSURLProtocol implementation, I take a mutable copy of the NSURLRequest, convert the URL to http: and send that to my server.
Everything works for HTTP GET requests. The problem I encounter is with POST requests. It seems like the UIWebView doesn't properly encode the form data in the HTTPBody if the request uses my custom protocol.
One work-around, since I'm using HTTPS for my server requests, is that I register my protocol handler to intercept http: instead of myprotocol: and I can convert all calls to https: This other question, here, pointed me toward that solution:
But I'm wondering if there's any alternative and/or better way of accomplishing what I want.
Instead of trying to use POST requests, one work around is to continue using GET requests for myprotocol:// URLs, but transform them in your NSURLProtocol implementation to an http:// and POST request to your server using the request query string as the body of the POST.
The worry with using GET requests to send large amounts of data is that somewhere along the request chain, the request line might get truncated. This appears to not be a problem, however, with locally-implemented protocols.
I wrote a short Cordova test app to experiment and I found that I was able to send through a little over 1 MiB of data without trouble to the HTTP request echoing service http://http-echo.jgate.de/
Here is my startLoading implementation:
- (void)startLoading {
NSURL *url = [[self request] URL];
NSString *query = [url query];
// Create a copy of `url` without the query string.
url = [[[NSURL alloc] initWithScheme:#"http" host:#"http-echo.jgate.de" path:[url path]] autorelease];
NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:url];
[newRequest setHTTPMethod:#"POST"];
[newRequest setAllHTTPHeaderFields:[[self request] allHTTPHeaderFields]];
[newRequest addValue:#"close" forHTTPHeaderField:#"Connection"];
[newRequest addValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[newRequest setHTTPBody:[query dataUsingEncoding:NSUTF8StringEncoding]];
urlConnection = [[NSURLConnection alloc] initWithRequest:newRequest delegate:self];
if (urlConnection) {
receivedData = [[NSMutableData data] retain];
}
}
I then implemented the NSURLConnection protocol methods to forward to the appropriate NSURLProtocolClient method, but building up the response data in the case of Transfer-Encoding:chunked (as is the case for responses from http://http-echo.jgate.de/).
Unfortunately it looks like that http: and https: scheme requests are handled slightly differently than other (including custom) schemes by Foundation Framework. Obviously HTTPBody and HTTPBodyStream calls on relevant NSURLRequest returns always nil for former ones. This is decided already prior call of [NSURLProtocol canInitWithRequest] therefore custom NSURLProtocol implementation has no way of influencing that (it is too late).
It seems that different NSURLRequest class is used for http: and https: than 'a default one'. Default GnuStep implementation of this class returns always nil from HTTPBody and HTTPBodyStream calls. Therefore particular implementations (e.g. one under PhoneGap, likely part of Foundation Framework) choose NSURLRequest-type of class based on scheme prior consulting that with NSURLProtocol. For custom schemes, you get NSURLRequest that returns nil for both HTTPBody and HTTPBodyStream which effectively disables use of POST method (and other methods with body) in custom URI scheme handler.
Maybe there is a way how to influence decision of which NSURLRequest class is actually used but it is currently unknown to me.
As a workaround, you can still use http: or https: scheme and decide in [NSURLProtocol canInitWithRequest] based on other criteria (e.g. host name).
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 am searching for HTTP example for I-phone 3.0. i am doing SyncMl application , which is uses http based protocol to syncronise two databases (ie client and server ) Using POST and GET.So i will be sending data to server using POST and reading data using GET.If anybody has sample code or any hint what type framework would be used ??
I am going to assume you are interested in implementing some plain old HTTP client code. Requesting a web page etc.
I use NSURL to do my HTTP requests. It is pretty straightforward. You can read all about it on the NSURL Class Reference, but here is a snippet of sample code:
// set up your request
NSURL * url = [NSURL URLWithString:#"http://www.stackoverflow.com"];
NSURLRequest * request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
// create your connection with your request and a delegate (in this case
// the object making the request)
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
You just need to implement some delegate methods to handle the data responses
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
ASIHTTPRequest is a great framework for HTTP Requests.
From the ASIHTTPRequest site:
ASIHTTPRequest is an easy to use wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier. It is written in Objective-C and works in both Mac OS X and iPhone applications.
It is suitable performing basic HTTP requests and interacting with REST-based services (GET / POST / PUT / DELETE). The included ASIFormDataRequest subclass makes it easy to submit POST data and files using multipart/form-data.
There is also a Google group. The code is hosted on github.