- package com.xiva.service;
- import org.apache.axis2.context.MessageContext;
- import org.apache.axis2.context.ServiceContext;
- public class LoginService {
- public boolean login(String userName, String password) {
- MessageContext context = MessageContext.getCurrentMessageContext();
- ServiceContext ctx = context.getServiceContext();
- if ("admin".equals(userName) && "123456".equals(password)) {
- ctx.setProperty("userName", userName);
- ctx.setProperty("password", password);
- ctx.setProperty("msg", "登陸成功");
- return true;
- }
- ctx.setProperty("msg", "登陸失敗");
- return false;
- }
- public String getLoginMessage() {
- MessageContext context = MessageContext.getCurrentMessageContext();
- ServiceContext ctx = context.getServiceContext();
- return ctx.getProperty("userName") + "#" + ctx.getProperty("msg");
- }
- }
安裝前面提到的博客文章,發佈好這個Service.
下面就是在iPhone上的調用了。
先把代碼給出,我們再一個一個分析。
- //
- // SOAPDemoViewController.h
- // SOAPDemo
- //
- // Created by xiang xiva on 11-4-4.
- // Copyright 2011 __MyCompanyName__. All rights reserved.
- //
- #import <UIKit/UIKit.h>
- @interface SOAPDemoViewController : UIViewController <NSXMLParserDelegate>{
- IBOutlet UITextField *nameInput;
- IBOutlet UILabel *greeting;
- NSMutableData *webData;
- NSMutableString *soapResults;
- NSXMLParser *xmlParser;
- BOOL recordResults;
- }
- @property(nonatomic, retain) IBOutlet UITextField *nameInput;
- @property(nonatomic, retain) IBOutlet UILabel *greeting;
- @property(nonatomic, retain) NSMutableData *webData;
- @property(nonatomic, retain) NSMutableString *soapResults;
- @property(nonatomic, retain) NSXMLParser *xmlParser;
- -(IBAction)buttonClick: (id) sender;
- - (void)loginSOAP;
- @end
- //
- // SOAPDemoViewController.m
- // SOAPDemo
- //
- // Created by xiang xiva on 11-4-4.
- // Copyright 2011 __MyCompanyName__. All rights reserved.
- //
- #import "SOAPDemoViewController.h"
- @implementation SOAPDemoViewController
- @synthesize greeting, nameInput, webData, soapResults, xmlParser;
- /*
- // The designated initializer. Override to perform setup that is required before the view is loaded.
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // Custom initialization
- }
- return self;
- }
- */
- /*
- // Implement loadView to create a view hierarchy programmatically, without using a nib.
- - (void)loadView {
- }
- */
- /*
- - (void)viewDidLoad {
- [super viewDidLoad];
- }
- */
- /*
- // Override to allow orientations other than the default portrait orientation.
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
- // Return YES for supported orientations
- return (interfaceOrientation == UIInterfaceOrientationPortrait);
- }
- */
- - (void)didReceiveMemoryWarning {
- // Releases the view if it doesn't have a superview.
- [super didReceiveMemoryWarning];
- // Release any cached data, images, etc that aren't in use.
- }
- - (void)viewDidUnload {
- // Release any retained subviews of the main view.
- // e.g. self.myOutlet = nil;
- }
- -(IBAction)buttonClick:(id)sender
- {
- greeting.text = @"Getting time …";
- [nameInput resignFirstResponder];
- [self loginSOAP];
- }
- #pragma mark -
- #pragma mark webService Data
- -(void)loginSOAP{
- recordResults = NO;
- //封裝soap請求消息
- NSString *soapMessage = [NSString stringWithFormat:
- @"<?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/\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">\n"
- "<soap:Body>\n"
- "<login xmlns=\"http://service.xiva.com\">\n"
- "<userName>admin"
- "</userName>"
- "<password>123456"
- "</password>"
- "</login>\n"
- "</soap:Body>\n"
- "</soap:Envelope>\n"
- ];
- NSLog(@"%a",soapMessage);
- //請求發送到的路徑
- NSURL *url = [NSURL URLWithString:@"http://192.168.0.64:8080/axis2/services/LoginService"];
- NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
- NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
- //以下對請求信息添加屬性前四句是必有的,第五句是soap信息。
- [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
- [theRequest addValue: @"http://service.xiva.com/login" forHTTPHeaderField:@"SOAPAction"];
- [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
- [theRequest setHTTPMethod:@"POST"];
- [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
- //請求
- NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
- //如果連接已經建好,則初始化data
- if( theConnection )
- {
- webData = [[NSMutableData data] retain];
- }
- else
- {
- NSLog(@"theConnection is NULL");
- }
- }
- -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- {
- [webData setLength: 0];
- NSLog(@"connection: didReceiveResponse:1");
- }
- -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- {
- [webData appendData:data];
- NSLog(@"connection: didReceiveData:%a", [webData length]);
- }
- //如果電腦沒有連接網絡,則出現此信息(不是網絡服務器不通)
- -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- {
- NSLog(@"ERROR with theConenction");
- [connection release];
- [webData release];
- }
- -(void)connectionDidFinishLoading:(NSURLConnection *)connection
- {
- NSLog(@"3 DONE. Received Bytes: %d", [webData length]);
- NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
- NSLog(@"%a",theXML);
- [theXML release];
- //重新加載xmlParser
- if( xmlParser )
- {
- [xmlParser release];
- }
- xmlParser = [[NSXMLParser alloc] initWithData: webData];
- [xmlParser setDelegate: self];
- [xmlParser setShouldResolveExternalEntities: YES];
- [xmlParser parse];
- [connection release];
- //[webData release];
- }
- -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
- attributes: (NSDictionary *)attributeDict
- {
- NSLog(@"4 parser didStarElemen: namespaceURI: attributes:");
- if( [elementName isEqualToString:@"soap:Fault"])
- {
- if(!soapResults)
- {
- soapResults = [[NSMutableString alloc] init];
- }
- recordResults = YES;
- }
- }
- -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
- {
- NSLog(@"5 parser: foundCharacters:");
- NSLog(@"recordResults:%@",string);
- if( recordResults )
- {
- [soapResults appendString: string];
- }
- }
- -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
- {
- NSLog(@"6 parser: didEndElement:");
- if( [elementName isEqualToString:@"ns:return"])
- {
- NSLog(@"MSG");
- }
- if( [elementName isEqualToString:@"getOffesetUTCTimeResult"])
- {
- recordResults = FALSE;
- greeting.text = [[[NSString init]stringWithFormat:@"第%@時區的時間是: ",nameInput.text] stringByAppendingString:soapResults];
- [soapResults release];
- soapResults = nil;
- NSLog(@"hoursOffset result");
- }
- }
- - (void)parserDidStartDocument:(NSXMLParser *)parser{
- NSLog(@"-------------------start--------------");
- }
- - (void)parserDidEndDocument:(NSXMLParser *)parser{
- NSLog(@"-------------------end--------------");
- }
- - (void)dealloc {
- [super dealloc];
- }
- @end
在iPhone你直接創建一個視圖應用即可。
既然集成了NSXMLParserDelegate的協議,那麼我們便可使用這個協議上的方法。
關於connection的方法和xml的方法在此不用多說了;看看方法名大家就知道用途了。
第一個難點:
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
這句話中的soapMessage的拼接。
- NSString *soapMessage = [NSString stringWithFormat:
- @"<?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/\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">\n"
- "<soap:Body>\n"
- "<login xmlns=\"http://service.xiva.com\">\n"
- "<userName>admin"
- "</userName>"
- "<password>123456"
- "</password>"
- "</login>\n"
- "</soap:Body>\n"
- "</soap:Envelope>\n"
- ];
除了下面這段代碼,其他都是一些系統設置,
"<login xmlns=\"http://service.xiva.com\">\n"
"<userName>admin"
"</userName>"
"<password>123456"
"</password>"
"</login>\n"
上面代碼中第一行的login,代表我們要調用的方法;xmlns中存放的是命名空間,http://service.xiva.com
service.xiva.com就是java中我們包位置的顛倒。
第二,三行代碼我們給login傳遞一個叫userName的參數,值爲admin
第四,五行代碼我們給login傳遞一個叫password的參數,值爲123456
第二個難點:
- NSURL *url = [NSURL URLWithString:@"http://192.168.0.64:8080/axis2/services/LoginService"];
- NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
- NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
- //以下對請求信息添加屬性前四句是必有的,第五句是soap信息。
- [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
- [theRequest addValue: @"http://service.xiva.com/login" forHTTPHeaderField:@"SOAPAction"];
- [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
- [theRequest setHTTPMethod:@"POST"];
- [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
首先url,是指我們調用該方法的地址,
第二行初始化一個request給我們的connection調用,
第三行和第七行我們在設置內容的長度
第四行,是註釋
第五行,設置http內容的type
第六行,是設置我們soapAction;也就是我們webService調用的方法,命名空間/方法名
第八行設置http的發送方式,爲post。(不知道用get會怎麼樣?)
第九行設置整個Body的內容,也就是我們之前拼接的那個soapMessage。