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