iPhone调用java的webService

Java代码   收藏代码
  1. package com.xiva.service;  
  2. import org.apache.axis2.context.MessageContext;  
  3. import org.apache.axis2.context.ServiceContext;  
  4.   
  5. public class LoginService {  
  6.       
  7.     public boolean login(String userName, String password) {  
  8.         MessageContext context = MessageContext.getCurrentMessageContext();  
  9.         ServiceContext ctx = context.getServiceContext();  
  10.         if ("admin".equals(userName) && "123456".equals(password)) {  
  11.             ctx.setProperty("userName", userName);  
  12.             ctx.setProperty("password", password);  
  13.             ctx.setProperty("msg""登陆成功");  
  14.             return true;  
  15.         }  
  16.         ctx.setProperty("msg""登陆失败");  
  17.         return false;  
  18.     }  
  19.       
  20.     public String getLoginMessage() {  
  21.         MessageContext context = MessageContext.getCurrentMessageContext();  
  22.         ServiceContext ctx = context.getServiceContext();  
  23.         return ctx.getProperty("userName") + "#" + ctx.getProperty("msg");  
  24.     }  
  25.       
  26. }  
 

安装前面提到的博客文章,发布好这个Service.

 

下面就是在iPhone上的调用了。

 

先把代码给出,我们再一个一个分析。

 

Soapdemoviewcontroller的头文件代码   收藏代码
  1. //  
  2. //  SOAPDemoViewController.h  
  3. //  SOAPDemo  
  4. //  
  5. //  Created by xiang xiva on 11-4-4.  
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.  
  7. //  
  8.   
  9. #import <UIKit/UIKit.h>  
  10.   
  11. @interface SOAPDemoViewController : UIViewController <NSXMLParserDelegate>{  
  12.       
  13.     IBOutlet UITextField *nameInput;  
  14.     IBOutlet UILabel *greeting;  
  15.       
  16.     NSMutableData *webData;   
  17.     NSMutableString *soapResults;  
  18.     NSXMLParser *xmlParser;  
  19.     BOOL recordResults;   
  20. }  
  21.   
  22. @property(nonatomic, retain) IBOutlet UITextField *nameInput;  
  23. @property(nonatomic, retain) IBOutlet UILabel *greeting;  
  24.   
  25. @property(nonatomic, retain) NSMutableData *webData;  
  26. @property(nonatomic, retain) NSMutableString *soapResults;  
  27. @property(nonatomic, retain) NSXMLParser *xmlParser;  
  28.   
  29. -(IBAction)buttonClick: (id) sender;  
  30. - (void)loginSOAP;  
  31. @end  
 

 

Soapdemoviewcontroller的实现代码代码   收藏代码
  1. //  
  2. //  SOAPDemoViewController.m  
  3. //  SOAPDemo  
  4. //  
  5. //  Created by xiang xiva on 11-4-4.  
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.  
  7. //  
  8.   
  9. #import "SOAPDemoViewController.h"  
  10.   
  11. @implementation SOAPDemoViewController  
  12.   
  13. @synthesize greeting, nameInput, webData, soapResults, xmlParser;  
  14.   
  15. /*  
  16. // The designated initializer. Override to perform setup that is required before the view is loaded.  
  17. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {  
  18.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  19.     if (self) {  
  20.         // Custom initialization  
  21.     }  
  22.     return self;  
  23. }  
  24. */  
  25.   
  26. /*  
  27. // Implement loadView to create a view hierarchy programmatically, without using a nib.  
  28. - (void)loadView {  
  29. }  
  30. */  
  31.   
  32.   
  33. /*  
  34. - (void)viewDidLoad {  
  35.     [super viewDidLoad];  
  36. }  
  37. */  
  38.   
  39.   
  40. /*  
  41. // Override to allow orientations other than the default portrait orientation.  
  42. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {  
  43.     // Return YES for supported orientations  
  44.     return (interfaceOrientation == UIInterfaceOrientationPortrait);  
  45. }  
  46. */  
  47.   
  48. - (void)didReceiveMemoryWarning {  
  49.     // Releases the view if it doesn't have a superview.  
  50.     [super didReceiveMemoryWarning];  
  51.       
  52.     // Release any cached data, images, etc that aren't in use.  
  53. }  
  54.   
  55. - (void)viewDidUnload {  
  56.     // Release any retained subviews of the main view.  
  57.     // e.g. self.myOutlet = nil;  
  58. }  
  59.   
  60. -(IBAction)buttonClick:(id)sender  
  61. {  
  62.     greeting.text = @"Getting time …";    
  63.     [nameInput resignFirstResponder];  
  64.     [self loginSOAP];  
  65. }  
  66.   
  67. #pragma mark -  
  68. #pragma mark webService Data  
  69.   
  70. -(void)loginSOAP{  
  71.     recordResults = NO;  
  72.     //封装soap请求消息  
  73.     NSString *soapMessage = [NSString stringWithFormat:  
  74.                              @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"  
  75.                              "<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"  
  76.                              "<soap:Body>\n"  
  77.                              "<login xmlns=\"http://service.xiva.com\">\n"  
  78.                              "<userName>admin"  
  79.                              "</userName>"  
  80.                              "<password>123456"  
  81.                              "</password>"  
  82.                              "</login>\n"  
  83.                              "</soap:Body>\n"  
  84.                              "</soap:Envelope>\n"  
  85.                              ];  
  86.     NSLog(@"%a",soapMessage);  
  87.     //请求发送到的路径  
  88.     NSURL *url = [NSURL URLWithString:@"http://192.168.0.64:8080/axis2/services/LoginService"];  
  89.     NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];  
  90.     NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];  
  91.       
  92.     //以下对请求信息添加属性前四句是必有的,第五句是soap信息。  
  93.     [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];  
  94.     [theRequest addValue: @"http://service.xiva.com/login" forHTTPHeaderField:@"SOAPAction"];  
  95.       
  96.     [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];  
  97.     [theRequest setHTTPMethod:@"POST"];  
  98.     [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];  
  99.       
  100.     //请求  
  101.      NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];  
  102.       
  103.     //如果连接已经建好,则初始化data  
  104.     if( theConnection )  
  105.     {  
  106.         webData = [[NSMutableData data] retain];  
  107.     }  
  108.     else  
  109.     {  
  110.         NSLog(@"theConnection is NULL");  
  111.     }  
  112. }  
  113.   
  114. -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  
  115. {  
  116.     [webData setLength: 0];  
  117.     NSLog(@"connection: didReceiveResponse:1");  
  118. }  
  119. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  
  120. {  
  121.     [webData appendData:data];  
  122.     NSLog(@"connection: didReceiveData:%a", [webData length]);  
  123.       
  124. }  
  125.   
  126. //如果电脑没有连接网络,则出现此信息(不是网络服务器不通)  
  127. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  
  128. {  
  129.     NSLog(@"ERROR with theConenction");  
  130.     [connection release];  
  131.     [webData release];  
  132. }  
  133. -(void)connectionDidFinishLoading:(NSURLConnection *)connection  
  134. {  
  135.     NSLog(@"3 DONE. Received Bytes: %d", [webData length]);  
  136.     NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];  
  137.     NSLog(@"%a",theXML);  
  138.     [theXML release];  
  139.       
  140.     //重新加載xmlParser  
  141.     if( xmlParser )  
  142.     {  
  143.         [xmlParser release];  
  144.     }  
  145.       
  146.     xmlParser = [[NSXMLParser alloc] initWithData: webData];  
  147.     [xmlParser setDelegate: self];  
  148.     [xmlParser setShouldResolveExternalEntities: YES];  
  149.     [xmlParser parse];  
  150.       
  151.     [connection release];  
  152.     //[webData release];  
  153. }  
  154.   
  155. -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName  
  156.    attributes: (NSDictionary *)attributeDict  
  157. {  
  158.     NSLog(@"4 parser didStarElemen: namespaceURI: attributes:");  
  159.       
  160.     if( [elementName isEqualToString:@"soap:Fault"])  
  161.     {  
  162.         if(!soapResults)  
  163.         {  
  164.             soapResults = [[NSMutableString alloc] init];  
  165.         }  
  166.         recordResults = YES;  
  167.     }  
  168.       
  169. }  
  170. -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string  
  171. {  
  172.     NSLog(@"5 parser: foundCharacters:");  
  173.     NSLog(@"recordResults:%@",string);  
  174.     if( recordResults )  
  175.     {  
  176.         [soapResults appendString: string];  
  177.     }  
  178.       
  179. }  
  180. -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName  
  181. {  
  182.     NSLog(@"6 parser: didEndElement:");  
  183.       
  184.     if( [elementName isEqualToString:@"ns:return"])  
  185.     {  
  186.         NSLog(@"MSG");  
  187.     }  
  188.       
  189.     if( [elementName isEqualToString:@"getOffesetUTCTimeResult"])  
  190.     {  
  191.         recordResults = FALSE;  
  192.         greeting.text = [[[NSString init]stringWithFormat:@"第%@时区的时间是: ",nameInput.text] stringByAppendingString:soapResults];  
  193.         [soapResults release];  
  194.         soapResults = nil;  
  195.         NSLog(@"hoursOffset result");  
  196.     }  
  197.       
  198. }  
  199. - (void)parserDidStartDocument:(NSXMLParser *)parser{  
  200.     NSLog(@"-------------------start--------------");  
  201. }  
  202. - (void)parserDidEndDocument:(NSXMLParser *)parser{  
  203.     NSLog(@"-------------------end--------------");  
  204. }  
  205.   
  206.   
  207. - (void)dealloc {  
  208.     [super dealloc];  
  209. }  
  210.   
  211. @end  
 

在iPhone你直接创建一个视图应用即可。

 

既然集成了NSXMLParserDelegate的协议,那么我们便可使用这个协议上的方法。

 

关于connection的方法和xml的方法在此不用多说了;看看方法名大家就知道用途了。

 

 

第一个难点:

[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

这句话中的soapMessage的拼接。

 

 

 

Soapmessage 代码   收藏代码
  1. NSString *soapMessage = [NSString stringWithFormat:  
  2.                              @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"  
  3.                              "<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"  
  4.                              "<soap:Body>\n"  
  5.                              "<login xmlns=\"http://service.xiva.com\">\n"  
  6.                              "<userName>admin"  
  7.                              "</userName>"  
  8.                              "<password>123456"  
  9.                              "</password>"  
  10.                              "</login>\n"  
  11.                              "</soap:Body>\n"  
  12.                              "</soap:Envelope>\n"  
  13.                              ];  

 

除了下面这段代码,其他都是一些系统设置,

 

"<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

 

 

第二个难点:

 

 

Nsmutableurlrequest的参数值代码   收藏代码
  1. NSURL *url = [NSURL URLWithString:@"http://192.168.0.64:8080/axis2/services/LoginService"];  
  2. NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];  
  3. NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];  
  4. //以下对请求信息添加属性前四句是必有的,第五句是soap信息。  
  5. [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];  
  6. [theRequest addValue: @"http://service.xiva.com/login" forHTTPHeaderField:@"SOAPAction"];  
  7. [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];  
  8. [theRequest setHTTPMethod:@"POST"];  
  9. [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];  
 

首先url,是指我们调用该方法的地址,

第二行初始化一个request给我们的connection调用,

第三行和第七行我们在设置内容的长度

第四行,是注释

第五行,设置http内容的type

第六行,是设置我们soapAction;也就是我们webService调用的方法,命名空间/方法名

第八行设置http的发送方式,为post。(不知道用get会怎么样?)

第九行设置整个Body的内容,也就是我们之前拼接的那个soapMessage。


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值