从iPad调用Web service

来源:互联网 发布:mac文件夹消失 编辑:程序博客网 时间:2024/05/22 03:22

1, 建立SOAP请求包:

NSString *soapMsg =    [NSString stringWithFormat:        @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"         "<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/\">"         "<soap:Body>"         "<FindCountryAsXml xmlns=\"http://www.ecubicle.net/webservices/\">"         "<V4IPAddress>%@</V4IPAddress>"         "</FindCountryAsXml>"         "</soap:Body>"         "</soap:Envelope>",  ipAddress.text];

2.建立调用请求URL对象,使用NSMutableURLRequest and NSURL实例

NSURL *url = [NSURL URLWithString:@"http://www.ecubicle.net/iptocountry.asmx"];    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];

3.构筑请求内容,如Content-Type, SOAPAction, and Content-Length. 并且设定HTTP method and HTTP body

NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];    [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];    [req addValue:@"http://www.ecubicle.net/webservices/FindCountryAsXml"        forHTTPHeaderField:@"SOAPAction"];    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];    [req setHTTPMethod:@"POST"];    [req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];


4.在实际请求Web service前, 启动请求等待动画, 提供一个可视化的提示给用户,说明正在请求Web service:

[activityIndicator startAnimating];
5.建立和Web service的连接 

conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];    if (conn) {        webData = [[NSMutableData data] retain];    }
6.其他的和连接数据库的方式是一样的

  当请求结束后,

-(void) connectionDidFinishLoading:(NSURLConnection *) connection {    NSLog(@"DONE. Received Bytes: %d", [webData length]);    NSString *theXML = [[NSString alloc]                        initWithBytes: [webData mutableBytes]                        length:[webData length]                        encoding:NSUTF8StringEncoding];    //---shows the XML---    NSLog(theXML);    [theXML release];    [activityIndicator stopAnimating];    [connection release];    [webData release];}


原创粉丝点击