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。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章