首先用到一個手機歸屬地查詢的服務網站。
http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx
SOAP是簡單對象訪問協議,它可看成是HTTP與XML的結合,其中XML部分是作為HTTP報文的實體主體部分
[webData setLength: 0]; //注意這里需要改正一下:webData=[NSMutableData alloc ]init];
1、運行Xcode 4.4.1,新建一個Single View Application,名稱為SOAP Test:
2、界面設計:打開ViewController.xib,設計界面如下所示: 在文本輸入框的Attribute Inspector中設置其Keyboard屬性為Number Pad。 3、之后向ViewController.h中,為文本輸入框創建OutLet映射,名稱為:phoneNumber;為“查詢”按鈕創建Action映射,事件類型為Touch Up Inside,名稱為:doQuery。建立映射的方法就是打開Assistant Editor,選中某一控件,按住Ctrl,拖向ViewController.h,可以參考前面的文章。 4、在ViewController.h中添加代碼: 4.1 在@interface那行最后添加代碼 <NSXMLParserDelegate, NSURLConnectionDelegate>
使ViewController遵守這兩個協議。前者用來解析XML,后者用于網絡連接。 4.2 在@end之前添加代碼 @property (strong, nonatomic) NSMutableData *webData; @property (strong, nonatomic) NSMutableString *soapResults; @property (strong, nonatomic) NSXMLParser *xmlParser; @property (nonatomic) BOOL elementFound; @property (strong, nonatomic) NSString *matchingElement; @property (strong, nonatomic) NSURLConnection *conn;
5、在ViewController.m中添加代碼: 5.1 在@implementation之后添加代碼 @synthesize webData; @synthesize soapResults; @synthesize xmlParser; @synthesize elementFound; @synthesize matchingElement; @synthesize conn;
5.2 實現doQuery方法 - (IBAction)doQuery:(id)sender { NSString *number = phoneNumber.text; // 設置我們之后解析XML時用的關鍵字,與響應報文中Body標簽之間的getMobileCodeInfoResult標簽對應 matchingElement = @"getMobileCodeInfoResult"; // 創建SOAP消息,內容格式就是網站上提示的請求報文的實體主體部分 NSString *soapMsg = [NSString stringWithFormat: @"<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<soap12:Envelope " "xmlns:xsi=\" http://www.w3.org/2001/XMLSchema-instance \" " "xmlns:xsd=\" http://www.w3.org/2001/XMLSchema \" " "xmlns:soap12=\" http://www.w3.org/2003/05/soap-envelope \">" "<soap12:Body>" "<getMobileCodeInfo xmlns=\" http://WebXml.com.cn/ \">" "<mobileCode>%@</mobileCode>" "<userID>%@</userID>" "</getMobileCodeInfo>" "</soap12:Body>" "</soap12:Envelope>", number, @""]; // 將這個XML字符串打印出來 NSLog(@"%@", soapMsg); // 創建URL,內容是前面的請求報文報文中第二行主機地址加上第一行URL字段 NSURL *url = [NSURL URLWithString: @" http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx "]; // 根據上面的URL創建一個請求 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]]; // 添加請求的詳細信息,與請求報文前半部分的各字段對應 [req addValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; // 設置請求行方法為POST,與請求報文第一行對應 [req setHTTPMethod:@"POST"]; // 將SOAP消息加到請求中 [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]]; // 創建連接 conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; if (conn) { webData = [NSMutableData data]; }}5.3 在@end之前添加代碼 #pragma mark -#pragma mark URL Connection Data Delegate Methods // 剛開始接受響應時調用-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response{ [webData setLength: 0]; //注意這里需要改正一下:webData=[NSMutableData alloc ]init];} // 每接收到一部分數據就追加到webData中-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *) data { [webData appendData:data];} // 出現錯誤時-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *) error { conn = nil; webData = nil;} // 完成接收數據時調用-(void) connectionDidFinishLoading:(NSURLConnection *) connection { NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; // 打印出得到的XML NSLog(@"%@", theXML); // 使用NSXMLParser解析出我們想要的結果 xmlParser = [[NSXMLParser alloc] initWithData: webData]; [xmlParser setDelegate: self]; [xmlParser setShouldResolveExternalEntities: YES]; [xmlParser parse];}
5.4 在@end之前添加代碼#pragma mark -#pragma mark XML Parser Delegate Methods // 開始解析一個元素名-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict { if ([elementName isEqualToString:matchingElement]) { if (!soapResults) { soapResults = [[NSMutableString alloc] init]; } elementFound = YES; }} // 追加找到的元素值,一個元素值可能要分幾次追加-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string { if (elementFound) { [soapResults appendString: string]; }} // 結束解析這個元素名-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:matchingElement]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"手機號碼信息" message:[NSString stringWithFormat:@"%@", soapResults] delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil]; [alert show]; elementFound = FALSE; // 強制放棄解析 [xmlParser abortParsing]; }} // 解析整個文件結束后- (void)parserDidEndDocument:(NSXMLParser *)parser { if (soapResults) { soapResults = nil; }} // 出錯時,例如強制結束解析- (void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { if (soapResults) { soapResults = nil; }}
#parm mark=======下面都是重復的了。=============
// 開始查詢- (IBAction)doQuery:(id)sender { NSString *number = phoneNumber.text; // 設置我們之后解析XML時用的關鍵字,與響應報文中Body標簽之間的getMobileCodeInfoResult標簽對應 matchingElement = @"getMobileCodeInfoResult"; // 創建SOAP消息,內容格式就是網站上提示的請求報文的實體主體部分 NSString *soapMsg = [NSString stringWithFormat: @"<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<soap12:Envelope " "xmlns:xsi=\" http://www.w3.org/2001/XMLSchema-instance \" " "xmlns:xsd=\" http://www.w3.org/2001/XMLSchema \" " "xmlns:soap12=\" http://www.w3.org/2003/05/soap-envelope \">" "<soap12:Body>" "<getMobileCodeInfo xmlns=\" http://WebXml.com.cn/ \">" "<mobileCode>%@</mobileCode>" "<userID>%@</userID>" "</getMobileCodeInfo>" "</soap12:Body>" "</soap12:Envelope>", number, @""]; // 將這個XML字符串打印出來 NSLog(@"%@", soapMsg); // 創建URL,內容是前面的請求報文報文中第二行主機地址加上第一行URL字段 NSURL *url = [NSURL URLWithString: @" http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx "]; // 根據上面的URL創建一個請求 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]]; // 添加請求的詳細信息,與請求報文前半部分的各字段對應 [req addValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; // 設置請求行方法為POST,與請求報文第一行對應 [req setHTTPMethod:@"POST"]; // 將SOAP消息加到請求中 [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]]; // 創建連接 conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; if (conn) { webData = [NSMutableData data]; }}5.3 在@end之前添加代碼#pragma mark -#pragma mark URL Connection Data Delegate Methods // 剛開始接受響應時調用-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response{ [webData setLength: 0];} // 每接收到一部分數據就追加到webData中-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *) data { [webData appendData:data];} // 出現錯誤時-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *) error { conn = nil; webData = nil;} // 完成接收數據時調用-(void) connectionDidFinishLoading:(NSURLConnection *) connection { NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; // 打印出得到的XML NSLog(@"%@", theXML); // 使用NSXMLParser解析出我們想要的結果 xmlParser = [[NSXMLParser alloc] initWithData: webData]; [xmlParser setDelegate: self]; [xmlParser setShouldResolveExternalEntities: YES]; [xmlParser parse];}
5.4 在@end之前添加代碼#pragma mark -#pragma mark XML Parser Delegate Methods // 開始解析一個元素名-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict { if ([elementName isEqualToString:matchingElement]) { if (!soapResults) { soapResults = [[NSMutableString alloc] init]; } elementFound = YES; }} // 追加找到的元素值,一個元素值可能要分幾次追加-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string { if (elementFound) { [soapResults appendString: string]; }} // 結束解析這個元素名-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:matchingElement]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"手機號碼信息" message:[NSString stringWithFormat:@"%@", soapResults] delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil]; [alert show]; elementFound = FALSE; // 強制放棄解析 [xmlParser abortParsing]; }} // 解析整個文件結束后- (void)parserDidEndDocument:(NSXMLParser *)parser { if (soapResults) { soapResults = nil; }} // 出錯時,例如強制結束解析- (void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { if (soapResults) { soapResults = nil; }}
6、運行
其中,輸入號碼時單擊查詢,打印出的響應XML如下: <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap=" http://www.w3.org/2003/05/soap-envelope " xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xmlns:xsd=" http://www.w3.org/2001/XMLSchema "> <soap:Body> <getMobileCodeInfoResponse xmlns=" http://WebXml.com.cn/ "> <getMobileCodeInfoResult>151898XXXXX:江蘇 南京 江蘇移動全球通卡 </getMobileCodeInfoResult> </getMobileCodeInfoResponse> </soap:Body></soap:Envelope>
上面的XML進行了縮進處理,實際上打印出來的是一行。
|
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
