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

时间:2022-09-24 21:32:57

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

  • HelloWorld.java
/**
*
*/
package com.alcor.jws.test;

import javax.jws.WebMethod;
import javax.jws.WebService;

import org.apache.cxf.feature.Features;

/**
* @author 徐泽宇(roamer)
*
* 2010-7-10
*/
@WebService
@Features(features = "org.apache.cxf.feature.LoggingFeature")
public interface HelloWorld {

@WebMethod
String sayHi(String text);
@WebMethod

boolean userLogon(String username,String userpasswd);
}
  • HelloWorldImpl.java

/**
*
*/
package com.alcor.jws.test;

import org.apache.cxf.feature.Features;
import org.apache.log4j.Logger;

import javax.jws.WebMethod;
import javax.jws.WebService;


/**
* @author 徐泽宇(roamer)
*
* 2010-7-10
*/
@WebService
@Features(features = "org.apache.cxf.feature.LoggingFeature")
public class HelloWorldImpl implements HelloWorld {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(HelloWorldImpl.class);


@WebMethod
public String sayHi(String text) {
if (logger.isDebugEnabled()) {
logger.debug("sayHi(String) - start"); //$NON-NLS-1$
}

String returnString = "Hello,你好: " + text;
if (logger.isDebugEnabled()) {
logger.debug("返回内容:"+returnString);
logger.debug("sayHi(String) - end"); //$NON-NLS-1$
}
return returnString;
}

@WebMethod
public boolean userLogon(String username ,String userpasswd)
{
logger.debug("用户名是:"+username+"口令是:"+userpasswd);
if (username.equalsIgnoreCase("admin"))
{
return true;
}else{
return false;
}
}
}

  • java 的web service 访问客户端

/**
*
*/
package com.alcor.jws.test;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

/**
* @author 徐泽宇(roamer)
*
* 2010-7-10
*/
public class Client {

private Client() {
}

public static void main(String args[]) throws Exception {
/*第一种方法,通过配置文件来实现 begin
ApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/WebServiceClient.xml");

HelloWorld client = (HelloWorld) ctx.getBean("client");

String result = client.sayHi("Roamer");
System.out.println(result);

boolean logonResult = client.userLogon("roamer", "passwd");
System.out.println(logonResult);

logonResult = client.userLogon("admin", "passwd");
System.out.println(logonResult);
*/

JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setAddress("http://localhost:8080/SampleWebService/webservice/HelloWorld");
factory.setServiceClass(HelloWorld.class);
factory.getInInterceptors().add(new LoggingInInterceptor());
HelloWorld helloWorld = (HelloWorld) factory.create();
boolean msg = helloWorld.userLogon("admin","World");
System.out.println(msg);
}
}

2。iphone 客户端的编程

  • LogonViewController.h

//
// LogonViewController.h
// IManager
//
// Created by remote roamer on 11-11-22.
// Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>


@interface LogonViewController : UIViewController<NSXMLParserDelegate>
{
IBOutlet UITextField * userNameTextField;
IBOutlet UITextField * userPasswordTextField;
IBOutlet UIButton * userLogonButton;
IBOutlet UITextField * webServiceURL;
NSXMLParser *xmlParser;
BOOL logonResult;
NSMutableString *soapResults;
}

@property(nonatomic,retain) IBOutlet UITextField * userNameTextField;
@property(nonatomic,retain) IBOutlet UITextField * userPasswordTextField;
@property(nonatomic,retain) IBOutlet UIButton * userLogonButton;
@property(nonatomic,retain) IBOutlet UITextField * webServiceURL;
@property(nonatomic, retain) NSXMLParser *xmlParser;
@property(nonatomic,retain) NSMutableString * soapResults;

-(IBAction) logonButtonClick:(id)sender;
@end

  • LogonViewController.m
    //
    // LogonViewController.m
    // IManager
    //
    // Created by remote roamer on 11-11-22.
    // Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
    //

    #import "LogonViewController.h"


    @implementation LogonViewController

    @synthesize userNameTextField;
    @synthesize userPasswordTextField;
    @synthesize userLogonButton;
    @synthesize webServiceURL;
    @synthesize xmlParser;
    @synthesize soapResults;


    -(IBAction) logonButtonClick:(id)sender
    {
    logonResult = false;
    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"
    "<ns1:userLogon xmlns:ns1=\"http://localhost:8080/SampleWebService/webservice/HelloWorld/\">"
    "<arg0>%@</arg0>"
    "<arg1>%@</arg1>"
    "</ns1:userLogon>"
    "</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:@"http://localhost:8080/SampleWebService/webservice/HelloWorld/"];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

    //以下对请求信息添加属性前四句是必有的,
    [urlRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [urlRequest addValue: @"http://localhost:8080/SampleWebService/webservice/HelloWorld" forHTTPHeaderField:@"SOAPAction"];
    [urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];


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

    }

    //如果调用有错误,则出现此信息
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
    NSLog(@"ERROR with theConenction");
    UIAlertView * alert =
    [[UIAlertView alloc]
    initWithTitle:@"提示"
    message:[error description]
    delegate:self
    cancelButtonTitle:nil
    otherButtonTitles:@"OK", nil];
    [alert show];
    }

    //调用成功,获得soap信息
    -(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)responseData
    {
    NSString * returnSoapXML = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"返回的soap信息是:%@",returnSoapXML);
    //开始解析xml
    xmlParser = [[NSXMLParser alloc] initWithData: responseData];
    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities: YES];
    [xmlParser parse];
    if(logonResult){
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"登录成功" message:returnSoapXML delegate:nil cancelButtonTitle:@"ok" otherButtonTitles: nil];
    [alert show];
    }

    }

    //如果soap的返回字符串比较多。需要实现以下这个方法,配合 didReceiveData 方法来正确的接受到所有的soap字符串
    //原因是:如果soap的返回字符串比较多。didReceiveData 这个方法会多次被调用。如果把soap解析的功能直接写在didReceiveData这个方法里面。会出现错误。这个时候,就需要 和connectionDidFinishLoading 联用。实现思路是:定义一个类变量NSMutableString * returnSoapXML;用于存放返回的soap字符串。
    //一旦有返回内容,获得soap信息,追加到结果字符串中
    //-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)responseData
    //{
    // [returnSoapXML appendString:[[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]];
    //}
    //最后在connectionDidFinishLoading 方法中实现,对完整的soap字符串的业务处理

    //数据全部接受成功以后调用
    /*
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    NSLog(@"从远程ws中调用获得客户简单信息的调用成功!");
    NSLog(@"返回的soap信息是:%@",returnSoapXML);
    //从soap 信息中解析出CusotmerInfo对象数组,并且保存到数据库中
    NSLog(@"开始保存ws返回的内容到本地数据库");
    [[[SoapRtnJsonParser alloc] init] parse2CustomersInfo:[returnSoapXML dataUsingEncoding:NSUTF8StringEncoding]];
    }
    */

    -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
    {

    NSLog(@"返回的soap内容中,return值是: %@",string);
    if ([string isEqualToString:@"true"])
    {
    logonResult = YES;
    }else{
    logonResult = NO;
    }
    }





    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    // Custom initialization
    }
    return self;
    }

    - (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.
    }

    #pragma mark - View lifecycle

    - (void)viewDidLoad
    {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    }

    - (void)viewDidUnload
    {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    }

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }

    @end

相关文章 :

其中要注意的几点。

  • <ns1:userLogon xmlns:ns1=\"http://localhost:8080/SampleWebService/webservice/HelloWorld/\">"
    "<arg0>%@</arg0>"
    "<arg1>%@</arg1>"
    "</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 的调用的内容

SOAP 1.1

The following is a sample SOAP 1.1 request and response. The placeholders shown need to be replaced with actual values.

 POST /MobileService.asmx HTTP/1.1
Host: 10.100.111.231
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/Logon"

<?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>
<Logon xmlns="http://tempuri.org/">
<userName>string</userName>
<password>string</password>
</Logon>
</soap:Body>
</soap:Envelope>

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?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>
<LogonResponse xmlns="http://tempuri.org/">
<LogonResult>string</LogonResult>
</LogonResponse>
</soap:Body>
</soap:Envelope>

SOAP 1.2

The following is a sample SOAP 1.2 request and response. The placeholders shown need to be replaced with actual values.

POST /MobileService.asmx HTTP/1.1
Host: 10.100.111.231
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<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">
<soap12:Body>
<Logon xmlns="http://tempuri.org/">
<userName>string</userName>
<password>string</password>
</Logon>
</soap12:Body>
</soap12:Envelope>

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<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">
<soap12:Body>
<LogonResponse xmlns="http://tempuri.org/">
<LogonResult>string</LogonResult>
</LogonResponse>
</soap12:Body>
</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中的代码一致。否则无法访问。

这个字符串的内容可以从asmx返回帮助界面来获得。