iphone ios 用xcode4.2开发 访问web service的功能

http://blog.csdn.net/panyaorui/article/details/8622990

1。后台利用 cxf 构建一个web service服务。

  • HelloWorld.java

[java] view plaincopy

  1. /**
  2. *
  3. */
  4. package com.alcor.jws.test;
  5. import javax.jws.WebMethod;
  6. import javax.jws.WebService;
  7. import org.apache.cxf.feature.Features;
  8. /**
  9. * @author 徐泽宇(roamer)
  10. *
  11. *         2010-7-10
  12. */
  13. @WebService
  14. @Features(features = "org.apache.cxf.feature.LoggingFeature")
  15. public interface HelloWorld {
  16. @WebMethod
  17. String sayHi(String text);
  18. @WebMethod
  19. boolean userLogon(String username,String userpasswd);
  20. }
  • HelloWorldImpl.java

[java] view plaincopy

  1. /**
  2. *
  3. */
  4. package com.alcor.jws.test;
  5. import org.apache.cxf.feature.Features;
  6. import org.apache.log4j.Logger;
  7. import javax.jws.WebMethod;
  8. import javax.jws.WebService;
  9. /**
  10. * @author 徐泽宇(roamer)
  11. *
  12. * 2010-7-10
  13. */
  14. @WebService
  15. @Features(features = "org.apache.cxf.feature.LoggingFeature")
  16. public class HelloWorldImpl implements HelloWorld {
  17. /**
  18. * Logger for this class
  19. */
  20. private static final Logger logger = Logger.getLogger(HelloWorldImpl.class);
  21. @WebMethod
  22. public String sayHi(String text) {
  23. if (logger.isDebugEnabled()) {
  24. logger.debug("sayHi(String) - start"); //$NON-NLS-1$
  25. }
  26. String returnString = "Hello,你好: " + text;
  27. if (logger.isDebugEnabled()) {
  28. logger.debug("返回内容:"+returnString);
  29. logger.debug("sayHi(String) - end"); //$NON-NLS-1$
  30. }
  31. return returnString;
  32. }
  33. @WebMethod
  34. public boolean userLogon(String username ,String userpasswd)
  35. {
  36. logger.debug("用户名是:"+username+"口令是:"+userpasswd);
  37. if (username.equalsIgnoreCase("admin"))
  38. {
  39. return true;
  40. }else{
  41. return false;
  42. }
  43. }
  44. }
  • java 的web service 访问客户端

[cpp] view plaincopy

  1. /**
  2. *
  3. */
  4. package com.alcor.jws.test;
  5. import org.apache.cxf.interceptor.LoggingInInterceptor;
  6. import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
  7. /**
  8. * @author 徐泽宇(roamer)
  9. *
  10. *         2010-7-10
  11. */
  12. public class Client {
  13. private Client() {
  14. }
  15. public static void main(String args[]) throws Exception {
  16. /*第一种方法,通过配置文件来实现  begin
  17. ApplicationContext ctx = new ClassPathXmlApplicationContext(    "META-INF/WebServiceClient.xml");
  18. HelloWorld client = (HelloWorld) ctx.getBean("client");
  19. String result = client.sayHi("Roamer");
  20. System.out.println(result);
  21. boolean logonResult = client.userLogon("roamer", "passwd");
  22. System.out.println(logonResult);
  23. logonResult = client.userLogon("admin", "passwd");
  24. System.out.println(logonResult);
  25. */
  26. JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
  27. factory.setAddress("http://localhost:8080/SampleWebService/webservice/HelloWorld");
  28. factory.setServiceClass(HelloWorld.class);
  29. factory.getInInterceptors().add(new LoggingInInterceptor());
  30. HelloWorld helloWorld = (HelloWorld) factory.create();
  31. boolean msg = helloWorld.userLogon("admin","World");
  32. System.out.println(msg);
  33. }
  34. }

2。iphone 客户端的编程

  • LogonViewController.h

[cpp] view plaincopy

  1. //
  2. //  LogonViewController.h
  3. //  IManager
  4. //
  5. //  Created by remote roamer on 11-11-22.
  6. //  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. @interface LogonViewController : UIViewController<NSXMLParserDelegate>
  10. {
  11. IBOutlet UITextField * userNameTextField;
  12. IBOutlet UITextField * userPasswordTextField;
  13. IBOutlet UIButton    * userLogonButton;
  14. IBOutlet UITextField * webServiceURL;
  15. NSXMLParser *xmlParser;
  16. BOOL logonResult;
  17. NSMutableString *soapResults;
  18. }
  19. @property(nonatomic,retain) IBOutlet UITextField * userNameTextField;
  20. @property(nonatomic,retain) IBOutlet UITextField * userPasswordTextField;
  21. @property(nonatomic,retain) IBOutlet UIButton    * userLogonButton;
  22. @property(nonatomic,retain) IBOutlet UITextField * webServiceURL;
  23. @property(nonatomic, retain) NSXMLParser *xmlParser;
  24. @property(nonatomic,retain) NSMutableString * soapResults;
  25. -(IBAction) logonButtonClick:(id)sender;
  26. @end
  • LogonViewController.m

    [cpp] view plaincopy

    1. //
    2. //  LogonViewController.m
    3. //  IManager
    4. //
    5. //  Created by remote roamer on 11-11-22.
    6. //  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
    7. //
    8. #import "LogonViewController.h"
    9. @implementation LogonViewController
    10. @synthesize userNameTextField;
    11. @synthesize userPasswordTextField;
    12. @synthesize userLogonButton;
    13. @synthesize webServiceURL;
    14. @synthesize xmlParser;
    15. @synthesize soapResults;
    16. -(IBAction) logonButtonClick:(id)sender
    17. {
    18. logonResult = false;
    19. NSString *soapMessage = [NSString stringWithFormat:
    20. @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
    21. "<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/\">"
    22. "<soap:Body>\n"
    23. "<ns1:userLogon xmlns:ns1=\"http://localhost:8080/SampleWebService/webservice/HelloWorld/\">"
    24. "<arg0>%@</arg0>"
    25. "<arg1>%@</arg1>"
    26. "</ns1:userLogon>"
    27. "</soap:Body>\n"
    28. "</soap:Envelope>",self.userNameTextField.text,self.userPasswordTextField.text];
    29. NSLog(@"调用webserivce的字符串是:%@",soapMessage);
    30. //请求发送到的路径
    31. NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
    32. NSURL *url = [NSURL URLWithString:@"http://localhost:8080/SampleWebService/webservice/HelloWorld/"];
    33. NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    34. //以下对请求信息添加属性前四句是必有的,
    35. [urlRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    36. [urlRequest addValue: @"http://localhost:8080/SampleWebService/webservice/HelloWorld" forHTTPHeaderField:@"SOAPAction"];
    37. [urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    38. [urlRequest setHTTPMethod:@"POST"];
    39. [urlRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    40. //请求
    41. NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    42. theConnection = nil;
    43. }
    44. //如果调用有错误,则出现此信息
    45. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    46. {
    47. NSLog(@"ERROR with theConenction");
    48. UIAlertView * alert =
    49. [[UIAlertView alloc]
    50. initWithTitle:@"提示"
    51. message:[error description]
    52. delegate:self
    53. cancelButtonTitle:nil
    54. otherButtonTitles:@"OK", nil];
    55. [alert show];
    56. }
    57. //调用成功,获得soap信息
    58. -(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)responseData
    59. {
    60. NSString * returnSoapXML = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    61. NSLog(@"返回的soap信息是:%@",returnSoapXML);
    62. //开始解析xml
    63. xmlParser = [[NSXMLParser alloc] initWithData: responseData];
    64. [xmlParser setDelegate:self];
    65. [xmlParser setShouldResolveExternalEntities: YES];
    66. [xmlParser parse];
    67. if(logonResult){
    68. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"登录成功" message:returnSoapXML delegate:nil cancelButtonTitle:@"ok" otherButtonTitles: nil];
    69. [alert show];
    70. }
    71. }
    72. //如果soap的返回字符串比较多。需要实现以下这个方法,配合 didReceiveData 方法来正确的接受到所有的soap字符串
    73. //原因是:如果soap的返回字符串比较多。didReceiveData 这个方法会多次被调用。如果把soap解析的功能直接写在didReceiveData这个方法里面。会出现错误。这个时候,就需要 和connectionDidFinishLoading 联用。实现思路是:定义一个类变量NSMutableString * returnSoapXML;用于存放返回的soap字符串。
    74. //一旦有返回内容,获得soap信息,追加到结果字符串中
    75. //-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)responseData
    76. //{
    77. //    [returnSoapXML appendString:[[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]];
    78. //}
    79. //最后在connectionDidFinishLoading 方法中实现,对完整的soap字符串的业务处理
    80. //数据全部接受成功以后调用
    81. /*
    82. - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    83. {
    84. NSLog(@"从远程ws中调用获得客户简单信息的调用成功!");
    85. NSLog(@"返回的soap信息是:%@",returnSoapXML);
    86. //从soap 信息中解析出CusotmerInfo对象数组,并且保存到数据库中
    87. NSLog(@"开始保存ws返回的内容到本地数据库");
    88. [[[SoapRtnJsonParser alloc] init] parse2CustomersInfo:[returnSoapXML dataUsingEncoding:NSUTF8StringEncoding]];
    89. }
    90. */
    91. -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
    92. {
    93. NSLog(@"返回的soap内容中,return值是: %@",string);
    94. if ([string isEqualToString:@"true"])
    95. {
    96. logonResult = YES;
    97. }else{
    98. logonResult = NO;
    99. }
    100. }
    101. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    102. {
    103. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    104. if (self) {
    105. // Custom initialization
    106. }
    107. return self;
    108. }
    109. - (void)didReceiveMemoryWarning
    110. {
    111. // Releases the view if it doesn‘t have a superview.
    112. [super didReceiveMemoryWarning];
    113. // Release any cached data, images, etc that aren‘t in use.
    114. }
    115. #pragma mark - View lifecycle
    116. - (void)viewDidLoad
    117. {
    118. [super viewDidLoad];
    119. // Do any additional setup after loading the view from its nib.
    120. }
    121. - (void)viewDidUnload
    122. {
    123. [super viewDidUnload];
    124. // Release any retained subviews of the main view.
    125. // e.g. self.myOutlet = nil;
    126. }
    127. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    128. {
    129. // Return YES for supported orientations
    130. return (interfaceOrientation == UIInterfaceOrientationPortrait);
    131. }
    132. @end

相关文章 :

其中要注意的几点。

  • [cpp] view plaincopy

    1. <ns1:userLogon xmlns:ns1=\"http://localhost:8080/SampleWebService/webservice/HelloWorld/\">"
    2. "<arg0>%@</arg0>"
    3. "<arg1>%@</arg1>"
    4. "</ns1:userLogon>"

    中web service 中的 userLogon方法的调用 要用ns1来引用。

  • 传递的参数 不能和 webservice的变量名来写。而只能写成 arg0 和 arg1 这种方式。我查阅其他网上资料,都是写成<username>和<userpasswd>这种element的形式。但是在我的这个演示中,如果写成这种方式。后台会无法获得传入的变量。而用arg0 这种方式是可以传入。我不清楚是否是和 java cxf的webservice搭建环境和版本有关。

注意:如果后台的WebService是.net开发的,调用的程序略有不同:

例如 后台的ws服务链接是 :http://10.100.111.231:9000/MobileService.asmx

那么访问这个url,会返回如下内容:

这个页面提示了SOAP 1.1 和 SOAP 1.2 的调用的内容

[html] view plaincopy

  1. SOAP 1.1
  2. The following is a sample SOAP 1.1 request and response. The placeholders shown need to be replaced with actual values.
  3. POST /MobileService.asmx HTTP/1.1
  4. Host: 10.100.111.231
  5. Content-Type: text/xml; charset=utf-8
  6. Content-Length: length
  7. SOAPAction: "http://tempuri.org/Logon"
  8. <?xml version="1.0" encoding="utf-8"?>
  9. <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/">
  10. <soap:Body>
  11. <Logon xmlns="http://tempuri.org/">
  12. <userName>string</userName>
  13. <password>string</password>
  14. </Logon>
  15. </soap:Body>
  16. </soap:Envelope>
  17. HTTP/1.1 200 OK
  18. Content-Type: text/xml; charset=utf-8
  19. Content-Length: length
  20. <?xml version="1.0" encoding="utf-8"?>
  21. <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/">
  22. <soap:Body>
  23. <LogonResponse xmlns="http://tempuri.org/">
  24. <LogonResult>string</LogonResult>
  25. </LogonResponse>
  26. </soap:Body>
  27. </soap:Envelope>
  28. SOAP 1.2
  29. The following is a sample SOAP 1.2 request and response. The placeholders shown need to be replaced with actual values.
  30. POST /MobileService.asmx HTTP/1.1
  31. Host: 10.100.111.231
  32. Content-Type: application/soap+xml; charset=utf-8
  33. Content-Length: length
  34. <?xml version="1.0" encoding="utf-8"?>
  35. <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">
  36. <soap12:Body>
  37. <Logon xmlns="http://tempuri.org/">
  38. <userName>string</userName>
  39. <password>string</password>
  40. </Logon>
  41. </soap12:Body>
  42. </soap12:Envelope>
  43. HTTP/1.1 200 OK
  44. Content-Type: application/soap+xml; charset=utf-8
  45. Content-Length: length
  46. <?xml version="1.0" encoding="utf-8"?>
  47. <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">
  48. <soap12:Body>
  49. <LogonResponse xmlns="http://tempuri.org/">
  50. <LogonResult>string</LogonResult>
  51. </LogonResponse>
  52. </soap12:Body>
  53. </soap12:Envelope>

那么,我们在objectiveC中代码应该写成

static NSString * wsURL = @"http://10.100.111.231:9000/MobileService.asmx";

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:Body>\n"
                             "<Logon xmlns=\"http://tempuri.org/\">"
                             "<userName>%@</userName>"
                             "<password>%@</password>"
                             "</Logon>"
                             "</soap:Body>\n"
                             "</soap:Envelope>",self.userNameTextField.text,self.userPasswordTextField.text];
    
    NSLog(@"调用webserivce的字符串是:%@",soapMessage);
    //请求发送到的路径
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",wsURL]];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
     //以下对请求信息添加属性前四句是必有的,
    [urlRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [urlRequest addValue:@"http://tempuri.org/Logon" forHTTPHeaderField:@"SOAPAction"];
    NSLog(@"SOAPAction is %@ ",@"http://tempuri.org/Logon");
    [urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

//请求
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    theConnection = nil;

注意红色的代码,这个http://tempurl.org/Logon 是要和 .net中的代码一致。否则无法访问。

时间: 2024-10-12 11:43:33

iphone ios 用xcode4.2开发 访问web service的功能的相关文章

iOS.访问 Web Service.MKNetworkKit_POST

#import <UIKit/UIKit.h> #import "T20140628025249NSNumber+Message.h" #import "T20140628025249NSString+URLEncoding.h" #import "MKNetworkEngine.h" #import "MKNetworkOperation.h" @interface T20140628025249ViewCont

iOS.访问 Web Service.同步GET请求方法

1.字符串转换为URL字符串NSString分类 #import <Foundation/Foundation.h> @interface NSString (URLEncoding) -(NSString *)URLEncodedString; -(NSString *)URLDecodedString; @end #import "T20140628013418NSString+URLEncoding.h" @implementation NSString (URLEn

iOS.访问 Web Service.异步GET请求方法

#import <UIKit/UIKit.h> #import "T20140628024750NSNumber+Message.h" #import "T20140628024750NSString+URLEncoding.h" @interface T20140628024750ViewController : UITableViewController<NSURLConnectionDelegate> @property (nonato

iOS.访问 Web Service.异步POST请求方法

#import <UIKit/UIKit.h> #import "T20140628024917NSNumber+Message.h" #import "T20140628024917NSString+URLEncoding.h" @interface T20140628024917ViewController : UITableViewController<NSURLConnectionDelegate> @property (nonato

iOS.访问 Web Service.MKNetworkKit_GET

#import <UIKit/UIKit.h> #import "T20140628025200NSNumber+Message.h" #import "T20140628025200NSString+URLEncoding.h" #import "MKNetworkEngine.h" #import "MKNetworkOperation.h" @interface T20140628025200ViewCont

iOS.访问 Web Service.使用下拉刷新控件

#import <UIKit/UIKit.h> #import "T20140628025702NSNumber+Message.h" #import "T20140628025702NSString+URLEncoding.h" @interface T20140628025702ViewController : UITableViewController @property (nonatomic,strong) NSMutableArray *lis

Java通过Axis访问Web Service

在使用Axis访问Web Service时,需要引入以下包(10个):axis-ant.jar.axis.jar.commons-discovery-0.2.jar.commons-logging-1.0.4.jar.jaxrpc.jar.log4j-1.2.8.jar.saaj.jar.wsdl4j-1.5.1.jar.activation-1.1.jar和mail-1.4.jar. 下面是一段Java代码的例子: 1 package demo; 2 import javax.xml.name

php curl 访问web service接口

利用curl访问web service接口代码如下: $apiUrl = 'http://test.com/test'; $accessToken = '123456789'; $header = ['Authorization: ' . $accessToken,'Content-Type:application/json']; $post = ['sku'=>[]]; $jsonPost = json_encode($post); $ch = curl_init(); curl_setopt

iOS 开发指南 第15章 访问Web Service之REST Web Service

***** 在电脑术语中,统一资源标识符(Uniform Resource Identifier,或URI)是一个用于标识某一互联网资源名称的字符串. 该种标识允许用户对任何(包括本地和互联网)的资源通过特定的协议进行交互操作.URI由包括确定语法和相关协议的方案所定义. Web上可用的每种资源 -HTML文档.图像.视频片段.程序等 - 由一个通用资源标识符(Uniform Resource Identifier, 简称"URI")进行定位. ***** 1 REST Web Ser