martes, 7 de junio de 2011

Connect to a web service



Before explaining how to connect to a Web service using Cocoa, you have to understand what is Web Service.
A Web Service is a site that contains methods and functions that can be consumed by other applications or websites. And whukeeping my methods and functions in the web service when I can have them in my application or website?
Sometimes you need to maintain the methods and functions outside of our application, when you need several applications or sites, re-use the same methods and web service functions, and not replicated for each application.
There are two types of web services

SOA. - Are the services that use a base architecture of communication messages.
ROA. - Are the services that use resources (resources) and communication based architecture, which is an implementation of REST, using technologies like XML, JSON, XHTML, plists.
Now going to the point in question, let's see how you can connect to a type of Web Service REST ...


For HTTP you can perform the following orders:


1.     GET
2.     POST
3.     PUT
4.     DELETE
5.     HEAD



In this case we will make a GET request to the service, so we need to follow the following steps:


- Know the web service information such as your address URI, or the methods that we check, and their respective parameters
HTTP-Request Ordering
-Obtain and crumble the result


The result that we will get will be something like this:


  1. <results>
  2. <head>
  3. <name>Nicolas</name>
  4. <entity>2</entity>
  5. <date>Tues Jun 07 06 GMT 2011</date>
  6. <description>Example of response</description>
  7. <method>ObtenerInformacion</method>
  8. <lon>-73.993525</lon>
  9. <title>iPhone Example</title>
  10. <url>http://iphoneexample:7074/.....</url>
  11. </head>
  12. </results>




Since we know that we're going to find once you make the request to the web service, let's move to write code:

  1. / / We set the web service URI (Remember that the @ is always strings below)
  2. NSString *urlWebService = @"http://ejemploiphone:7074/...";
  3.  
  4. / / Create an NSURL object with the web service
  5. NSURL *url = [NSURL URLWithString:urlWebService];
  6.  
  7. NSStringEncoding encoding;
  8. NSError *error;
  9.  
  10. NSString *doc = [NSString stringWithContentsOfURL:urlUsedEncoding:&encoding error:&error];
  11.  
  12. NSURLResponse *response;
  13. NSError *error;
  14. NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
  15.  
  16. //Handle the request
  17. NSData *urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
  18. NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];

No hay comentarios:

Publicar un comentario en la entrada