iOS SOAP protocol WebService article

Source: Internet
Author: User
Tags soap

This is an introduction to iOS using the SOAP protocol and WebService for communication.

I also recently made a small project, the use of this approach. Of course, now iOS use more webservice to restful majority. Think of this complex protocol soap, relatively few.

Talk less, start explaining:

First, talk about the principle

Soap is a protocol, specification. As long as the client sends a specific XML-formatted text, which is sent to the server side by post, the server side returns the corresponding XML format response.

So when we know the principle of soap, we can do it well.

Two, how to do iOS

A way to send a post can be, and then find the SOAP Send protocol message XML format, and finally receive, asynchronous receive, and then parse the return message on the line. Very simple.

Third, the specific procedure

In the VIEWCONTROL.M


#import "ViewController.h"


@interface Viewcontroller ()

@property (strong,nonatomic) Iboutletuitextfield *search;


@end


@implementation Viewcontroller


@synthesize WebData;

@synthesize Soapresults;

@synthesize Xmlparser;

@synthesize Elementfound;

@synthesize matchingelement;

@synthesize Conn;



-(ibaction) Search: (ID) sender

{

NSString *path=[[nsstring alloc] initwithformat:@ "/webservice/query/getresultbyname2"];

Nsmutabledictionary *param = [[Nsmutabledictionary alloc] init];

[param setvalue:@ "name" ForKey:self.search.text];

[Param setvalue:@ "pagenumber" forkey:@ "1"];

Mknetworkengine *engine = [[Mknetworkengine alloc] initwithhostname:@ "search.chinajob.com" Customheaderfields:nil] ;

Mknetworkoperation *op = [engine Operationwithpath:path params:param httpmethod:@ "POST"];

[Op addcompletionhandler:^ (mknetworkoperation *completedoperation) {

NSLog (@ "ResponseData:%@", [completedoperation responsestring]);

NSData *data = [Completedoperation responsedata];

Nsdictionary *resdict = [nsjsonserialization jsonobjectwithdata:data options: (nsjsonreadingallowfragments) error : nil];

[Self reloadinputviews];

} errorhandler:^ (Mknetworkoperation *errorop, Nserror *err)

//     {

NSLog (@ "error WY:%@", [err localizeddescription]);

//     }];

[Engine Enqueueoperation:op];

NSString *name = Self.search.text;

Set the keyword that we use when parsing XML, corresponding to the getmobilecodeinforesult tag between the body tag in the response message

Matchingelement =@ "name";

Create a SOAP message with the content format being the entity body part of the request message that is prompted on the Web site

NSString *soapmsg = [Nsstringstringwithformat:

@ "<soapenv:envelope xmlns:soapenv=\" http://schemas.xmlsoap.org/soap/envelope/\ "xmlns:web=\" http:// Webservice.kbhn/\ ">"

"<soapenv:Header/>"

"<soapenv:Body>"

"<web:getresultbyname2>"

"<!--optional:-->"

"<name>%@</name>"

"<!--optional:-->"

"<pageNumber>1</pageNumber>"

"</web:getresultbyname2>"

"</soapenv:Body>"

"</soapenv:Envelope>", Name, @ ""];

Print out this XML string

NSLog (@ "%@", soapmsg);

Creates a URL with the second row of host addresses in the previous request message message plus the first line URL field

Nsurl *url = [nsurlurlwithstring:@ "Http://search.chinajob.com/webservice/query"];

Create a request based on the URL above

Nsmutableurlrequest *req = [Nsmutableurlrequestrequestwithurl:url];

NSString *msglength = [nsstringstringwithformat:@ "%d", [soapmsglength]];

Add the details of the request, corresponding to each field in the first half of the request message

[Req addvalue:@ "Text/xml;charset=utf-8" forhttpheaderfield:@ "Content-type"];

[Req addvalue:msglengthforhttpheaderfield:@ "Content-length"];

Set the request line method to post, corresponding to the first line of the request message

[Req sethttpmethod:@ "POST"];

Adding a SOAP message to the request

[Req sethttpbody: [soapmsgdatausingencoding:nsutf8stringencoding]];

Create a connection

conn = [[Nsurlconnectionalloc] initWithRequest:reqdelegate:self];

IF (conn) {

WebData = [Nsmutabledatadata];

}

}


Called when the response is initially accepted

-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{

[webdatasetlength:0];

}


Append to WebData for every piece of data received

-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) Data {

[Webdataappenddata:data];

}


When an error occurs

-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) Error {

conn = nil;

WebData = nil;

}


Called when the receive data is completed

-(void) connectiondidfinishloading: (nsurlconnection *) connection {

NSString *thexml = [[Nsstringalloc] initwithbytes:[webdatamutablebytes]

Length:[webdatalength]

Encoding:nsutf8stringencoding];

Print out the resulting XML

NSLog (@ "%@", thexml);

Use Nsxmlparser to parse out the results we want

Xmlparser = [[Nsxmlparseralloc] initwithdata:webdata];

[Xmlparsersetdelegate:self];

[Xmlparsersetshouldresolveexternalentities:yes];

[Xmlparser parse];

}


Begin parsing an element name

-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName attributes: (nsdictionary *) attributedict {

if ([elementname isequaltostring:matchingelement]) {

if (!soapresults) {

Soapresults = [[Nsmutablestringalloc] init];

}

Elementfound = YES;

}

}


Append found element value, one element value may be appended several times

-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string {

if (elementfound) {

[Soapresultsappendstring:string];

}

}


End parsing this element name

-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName {

if ([elementname isequaltostring:matchingelement]) {

Uialertview *alert = [[Uialertviewalloc] initwithtitle:@ "mobile number Information"

message:[nsstringstringwithformat:@ "%@", Soapresults]

Delegate:self

cancelbuttontitle:@ "OK"

Otherbuttontitles:nil];

[Alertshow];

Elementfound = FALSE;

Force Abort resolution

[Xmlparserabortparsing];

}

}


After parsing the entire file

-(void) Parserdidenddocument: (Nsxmlparser *) Parser {

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.