Make Better Things



I like to make better things.

Call SOAP web service from iPhone

Here is my experience with calling SOAP web services from iPhone SDK.

For this tutorial i am using w3school’s CelsiusToFahrenheit SOAP web service example here you can find the docs for this service.

To call a SOAP service first i create a string with the SOAP request as follows.

NSString *soapMessage = @"<?xml version="1.0" encoding="utf-8"?>n"
	"<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">n"
	"<soap:Body>n"
	"<CelsiusToFahrenheit xmlns="http://tempuri.org/">n"
	"<Celsius>50</Celsius>n"
    "</CelsiusToFahrenheit>n"
	"</soap:Body>n"
	"</soap:Envelope>n";

After creating the SOAP request I create a NSMutableRequest to send this request to server.

 	NSURL *url = [NSURL URLWithString:@"http://w3schools.com/webservices/tempconvert.asmx"];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

	[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[theRequest addValue: @"http://tempuri.org/CelsiusToFahrenheit" forHTTPHeaderField:@"SOAPAction"];
	[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

	if( theConnection )
	{
		webData = [[NSMutableData data] retain];
	}
	else
	{
		NSLog(@"theConnection is NULL");
	}

After firing the request we can collect the XML response in the NSURLConnection’s delegate methods.


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSLog(@"ERROR with theConenction");
	[connection release];
	[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSLog(@"DONE. Received Bytes: %d", [webData length]);
	NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
	NSLog(@"%@",theXML);
	[theXML release];
}

After collecting the XML response in theXML string in -(void)connectionDidFinishLoading:(NSURLConnection *)connection
we can parse this string using TBXML for any other XML parser you like.

Category: iPhone

Tagged: ,

23 Responses

  1. jan says:

    Hi, did you use any API for this? iphone sdk natively supports soap? tnx

  2. [...] use this Link for using SOAP Webservice in [...]

  3. Katy says:

    Hi

    How can you parse two XMLs using the method you have provided?

  4. pcmuh says:

    hi,i use that code but u didnt how to use to run web service app exactly..i mean if u show use step by step it would be better or any idea u have pls help i need ….

    • Saurabh says:

      Actually I am in middle of writing something on web services. I’ll post soon on MBT.. meanwhile keep checking other post and subscribe to RSS.. Thanks..

  5. pcmuh says:

    thnk u we waiting for u..

  6. dong says:

    I built soap service and tested by calling soap service from jquery.ajax. It worked well.
    I follow the tut, but get the response is Bad Request
    could you give me the hint!
    thanks.

  7. pradeep says:

    HI HOW TO GIVE USER CREDEDENTIAL LIKE USER NAME AND PASSWORD BY SENDING SOAP REQUEST TO ACCESS SOAP RESPONSE THROUGH UI TEXTBOX

  8. Shashikant says:

    Dear Saurabh ,
    I am iPhone apps developer , working on soap but when iperform nslog of theXMl(in your) it show error and error is “Request format is invalid: Missing required soap:Body”
    and my soap message is given below:@”\n”
    “/\n”
    “/\n”
    “<PDALogin xmlns=\"http://tempuri.org/\n"
    "%@\n”
    “%@\n”
    “\n”
    “\n”
    “\n”
    I used this site for parsing
    http://mws.nameserverkatie.com/ws/mws.asmx?op=PDALogin
    where i am wrong please help me

  9. Deer says:

    Good one,
    Can be very good if you would able to provide parser and related all information…
    but any way nice
    want to change one thing in “soapMessage” as below

    NSString *soapMessage = @”\n”
    “\n”
    “\n”
    “\n”
    “50\n”
    “\n”
    “\n”
    “\n”;

  10. gaurav says:

    please send me full code of xcode, web service with example…

  11. Deepika says:

    nice post. really helpful

  12. Priyank shah says:

    hey i have done above this it works nicely and successfully . but problem now ahead is you have done for one function if i want to call soap request twice for different function and getting response from different related function. how it does? please help me…Thank You

  13. Priyank shah says:

    hey thanks saurabh for your valuable response.But i have done already what u tell me,but still it doesn’t work.

    first request done successfully for companyid then move to the client id done ok.

    secondly, control moves to the response now it gets first response for companyid so it gets receiveresponse,receivedata,connectiondidfinshloading(parsing successfully),didstartelement(it matches GetCompanyResponse succesfully),fondcharacter(it gets whole string(data) successfully),endelement for Getcompany till here it works nice and gets data for first request,

    Now,it loads again in response for getting client,this time it receive reponse(connection matches nicely),receivedata(connection matches nicely),connctiondidfinishloading(hereconnection matches and also done parsing i dont know it does or not) but while it comes in didstartelement this time it does not get the GetClientResponse it always show me GetCompanyResponse it reserved previous one only.

    i have post code at below now you optimize

    NSString *soapMessage = [NSString stringWithFormat:@"\n"
    "\n"
    "\n"
    " \n"
    "%@\n"

    "\n"
    "\n"
    "\n",cid];

    NSURL *url = [NSURL URLWithString:@"http://192.168.1.104:9018/projecttracker.asmx"];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    //theRequest=[ASIHTTPRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

    [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest addValue: @"http://tempuri.org/GetCompany" forHTTPHeaderField:@"SOAPAction"];

    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    // [theRequest st]
    theConnection =
    [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    [theConnection start];
    if( theConnection )
    {

    webData = [NSMutableData data];
    // webData =[NSDictionary dictionary];

    NSLog(@”Problem”);
    }
    else
    {
    NSLog(@”theConnection is NULL”);
    }
    //theConnection=nil;
    //—————————Client name ——————————

    NSString *soapMessage1 = [NSString stringWithFormat:@"\n"
    "\n"
    "\n"
    " \n"
    "%@\n"
    "\n"
    "\n"
    "\n",clid];

    // “%@\n”
    // “\n”
    NSURL *url1 = [NSURL URLWithString:@"http://192.168.1.104:9018/projecttracker.asmx"];
    NSMutableURLRequest *theRequest1 = [NSMutableURLRequest requestWithURL:url1];
    NSString *msgLength1 = [NSString stringWithFormat:@"%d", [soapMessage1 length]];

    [theRequest1 addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest1 addValue: @"http://tempuri.org/GetProject_Type_Id" forHTTPHeaderField:@"SOAPAction"];

    [theRequest1 addValue: msgLength1 forHTTPHeaderField:@"Content-Length"];
    [theRequest1 setHTTPMethod:@"POST"];
    [theRequest1 setHTTPBody: [soapMessage1 dataUsingEncoding:NSUTF8StringEncoding]];
    // [theRequest1
    theConnection1 =
    [[NSURLConnection alloc] initWithRequest:theRequest1 delegate:self];
    [theConnection1 start];
    if( theConnection1 )
    {
    webData1 = [NSMutableData data];
    // webData =[NSDictionary dictionary];

    NSLog(@”Problem client name “);
    }
    else
    {
    NSLog(@”theConnection is NULL”);
    }

    //—————————————————————————–
    }

    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
    if(connection == theConnection)
    {
    [webData setLength: 0];
    }
    else if(connection == theConnection1)
    {
    [webData1 setLength:0];
    }

    // [webData set]
    }

    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {

    if(connection == theConnection)
    {
    [webData appendData:data];
    }
    else if(connection == theConnection1)
    {
    [webData1 appendData:data];
    }
    // webData=data;
    }
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
    if(connection == theConnection)
    {
    NSLog(@”ERROR with theConenction”);
    }
    else if(connection ==theConnection1)
    {
    NSLog(@”ERROR with theConenction client name”);
    }

    }
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    if(connection == theConnection)
    {

    NSLog(@”DONE. Received Bytes: %d”, [webData length]);

    NSLog(@”webdata is :%@”,webData);
    NSString *theXML = [[NSString alloc] initWithBytes:
    [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    NSData *myData = [theXML dataUsingEncoding:NSUTF8StringEncoding];

    // NSData *myData=[theXML ];

    xmlParser = [[NSXMLParser alloc] initWithData:myData];

    // Don’t forget to set the delegate!
    xmlParser.delegate = self;
    [xmlParser parse];
    }
    else if(connection == theConnection1 )
    {

    NSLog(@”DONE. Received Bytes of client name: %d”, [webData length]);

    NSLog(@”webdata of client name is :%@”,webData);
    NSString *theXML1 = [[NSString alloc] initWithBytes:
    [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    NSData *myData1 = [theXML1 dataUsingEncoding:NSUTF8StringEncoding];

    // NSData *myData=[theXML ];

    xmlParser1 = [[NSXMLParser alloc] initWithData:myData1];

    // Don’t forget to set the delegate!
    xmlParser1.delegate = self;
    [xmlParser1 parse];

    }
    }

    -(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI qualifiedName:
    (NSString *)qName attributes:(NSDictionary *)attributeDict
    {
    // currentDescription=[NSArray alloc];
    [xmlParser setDelegate:self];
    [xmlParser1 setDelegate:self];

    if([elementName isEqualToString:@"GetCompanyResponse"])
    // if([elementName isEqualToString:@"GetClientResponse"])
    {
    currentDescription = [[NSString alloc] init];
    }
    else if([elementName isEqualToString:@"GetClientResponse"])
    {

    currentDescription1 = [[NSString alloc] init];
    }

    }

    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
    {

    if(parser == xmlParser)
    {
    currentDescription=string;

    //combinedarray=[[NSMutableArray alloc]init];

    descriptiondata=[currentDescription JSONValue];

    [self.companypickerview reloadAllComponents];
    //[companypickerview selectRow:0 inComponent:0 animated:YES];
    }
    else if(parser == xmlParser1)
    {
    currentDescription1=string;
    descriptiondata1=[currentDescription JSONValue];
    [self.clientnamepickerview reloadAllComponents];
    }
    }

    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
    {
    if([elementName isEqual: @"GetCompanyResult"])
    {
    NSLog(@”String result : %@”,currentDescription);
    }
    else if([elementName isEqual:@"GetClientResult"])
    {

    NSLog(@”string result of client name : %@”,currentDescription1);
    }

    //resultlabel.text=[currentDescription valueForKey:@"BUG_ID"];
    }

  14. Priyank shah says:

    hey i have seen that link.nice one even i get more another thing from that it really useful in even future app development.
    but is it suited in my code?

  15. Priyank shah says:

    hey saurabh hi still i m waiting for response. wellll somehow i come to know that previous response may be destroyed…

  16. Bhushan says:

    How to pass NSXMLElement as parameter to SOAP message? Like when we create soap message with StringFormat for sending string as parameter we used “%@” but if we want to send NSXMLElement as parameter the how we will send using soap message..

    And can u please tell me how to give out parameter to soap message?
    Please gives u r valuable feedback.
    Thanks in advance.

Leave a Reply