查询QQ是否在线(SOAP)

 今天作了个查询QQ是否在线的,效果图以下,web

http://webservice.webxml.com.cn/webservices/qqOnlineWebService.asmx
网络

得到腾讯QQ在线状态

输入参数:QQ号码 String,默认QQ号码:8698053。返回数据:String,Y = 在线;N = 离线;E = QQ号码错误;A = 商业用户验证失败;V = 免费用户超过数量app

查询结果没有设置为在线等,仍是Y,这个用switch就能够了,或者写一个专门的类用来反馈结果

 

 

 在xib中设置如上图,textfiled的键盘设置为数字键盘网站

 

 

声明文件内容                                                            
atom

#import <UIKit/UIKit.h>url

 

@interface YUViewController : UIViewController<NSXMLParserDelegate,NSURLConnectionDelegate>//前者用来解析XML,后者用于网络链接spa

@property (weak, nonatomic) IBOutlet UITextField *qq;.net

- (IBAction)doQuery:(id)sender;orm

 

@property (strong, nonatomic) NSMutableData *webData;xml

@property (strong, nonatomic) NSMutableString *soapResults;

@property (strong, nonatomic) NSXMLParser *xmlParser;

@property (nonatomic) BOOL elementFound;

@property (strong, nonatomic) NSString *matchingElement;

@property (strong, nonatomic) NSURLConnection *conn;

 

@end

 

 

//SOAP是简单对象访问协议,它可当作是HTTPXML的结合,其中XML部分是做为HTTP报文的实体主体部分。具体信息能够参考百度

//iOS中使用SOAP,须要咱们本身组装XML格式的字符串,当XML字符串比较长的时候会变得很麻烦。另外,咱们在写XML格式的字符串时也要常常使用转义字符“\”。这个是服务提供方 www.webxml.com.cn

 

实现文件内容                                          

//

// YUViewController.m

// atQQ

//

// Created by chen on 3/9/13.

// Copyright (c) 2013 IOSCHEN. All rights reserved.

//

 

#import "YUViewController.h"

 

@interface YUViewController ()

 

@end

 

@implementation YUViewController

@synthesize webData;

@synthesize soapResults;

@synthesize xmlParser;

@synthesize elementFound;

@synthesize matchingElement;

@synthesize conn;

- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

// 开始查询

- (IBAction)doQuery:(id)sender

{

    NSString *number =_qq.text;

    // 设置咱们以后解析XML时用的关键字,与响应报文中Body标签之间的qqCheckOnlineResult标签对应

    matchingElement = @"qqCheckOnlineResult";

    // 建立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>"

                         "<qqCheckOnline xmlns=\"http://WebXml.com.cn/\">"

                         "<qqCode>%@</qqCode>"

                         "</qqCheckOnline>"

                         "</soap12:Body>"

                         "</soap12:Envelope>", number];

    // 将这个XML字符串打印出来

    NSLog(@"%@", soapMsg);

    // 建立URL,内容是前面的请求报文报文中第二行主机地址加上第一行URL字段

    NSURL *url = [NSURL URLWithString: @"http://webservice.webxml.com.cn/webservices/qqOnlineWebService.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];

    }

   

    [_qq resignFirstResponder];

}

 

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

}

 

#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:@"QQ是否在线"

                                                       message:[NSString stringWithFormat:@"%@", soapResults]

                                                      delegate:self

                                             cancelButtonTitle:@"肯定"

                                             otherButtonTitles:nil];

        [alert show];

        elementFound = FALSE;

        // 强制放弃解析

        [xmlParser abortParsing];

       

        soapResults=nil;//防止查询两次的时候显示了两次的结果

    }

}

 

// 解析整个文件结束后

- (void)parserDidEndDocument:(NSXMLParser *)parser {

    if (soapResults) {

        soapResults = nil;

    }

}

 

// 出错时,例如强制结束解析

- (void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {

    if (soapResults) {

        soapResults = nil;

    }

}

@end

参考博文 http://my.oschina.net/plumsoft/blog/75277