`
xiang37
  • 浏览: 434316 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

iPhone调用java的webService

阅读更多

     写这个笔记之前,我也参考了一些文章,主要是在http://www.cocoachina.com/这个网站上搜索资料。

      webService大家可以看一个教程:

         http://www.cnblogs.com/hoojo/archive/2011/03/16/1985160.html谢谢这位博主对我提供的帮助。

         下面是我的webService代码:

 

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。

 

3
0
分享到:
评论
4 楼 xiang37 2013-03-18  
wwwang89 写道
这位大哥,你好!很感谢你分享的文章,写的很好,适合我们新手学习和研究!我想请教一个问题:我的服务器端返回的是一个json的字符串(调用的是服务器的一个比如login方法,直接return的),但是在我的Xcode端控制台输出的是一个类似xml格式的: "<soap:Envelope...... <out>这里是服务器返回的json字符串</out>,......还有其他的标签字符串。输出这种格式估计是setbody和封装的soapmessage导致的吧,我现在想直接输出或者得到我的那一串json字符串,或者是在我的xcode端是用什么(那个对象变量)来接收服务器端返回的字符串的?~~小弟先谢谢了!!

对不起,好久没有弄这个了,当初也是项目调研才写了这个的;我想给你一点建议的就是你可以按照XML格式解析出JSON,其实用到其他的封装,估计也是这么做的。解析出JSON后,再写一个递归函数解析的话,应该可以转换为你要的结果。
至于转换,你可以看看这个http://www.cocoachina.com/bbs/simple/?t110709.html。
3 楼 wwwang89 2013-03-18  
这位大哥,你好!很感谢你分享的文章,写的很好,适合我们新手学习和研究!我想请教一个问题:我的服务器端返回的是一个json的字符串(调用的是服务器的一个比如login方法,直接return的),但是在我的Xcode端控制台输出的是一个类似xml格式的: "<soap:Envelope...... <out>这里是服务器返回的json字符串</out>,......还有其他的标签字符串。输出这种格式估计是setbody和封装的soapmessage导致的吧,我现在想直接输出或者得到我的那一串json字符串,或者是在我的xcode端是用什么(那个对象变量)来接收服务器端返回的字符串的?~~小弟先谢谢了!!
2 楼 xiang37 2011-04-08  
jy1245626 写道
看到你的头像就很伤心

为什么?你也是道友?
1 楼 jy1245626 2011-04-08  
看到你的头像就很伤心

相关推荐

    C#调用JavaWebService

    调用WebService,最简单的办法当然是直接添加WEB引用,然后自动产生代理类,但是在调用JAVA的WebService时并没有这么简单,特别是对于SoapHeader的处理,通过C#添加Web引用方式访问JavaWebService的方法,除了string...

    delphi调用Java webservice实例

    标题 "Delphi调用Java WebService实例" 涉及的是在Delphi编程环境中如何与Java WebService进行交互的技术。Delphi是一款强大的Windows应用程序开发工具,而Java WebService则是一种基于标准的,跨平台的远程调用技术...

    .net调用java WebService

    ### .NET调用Java WebService的关键知识点 #### 一、背景与原理介绍 在实际的软件开发过程中,不同技术栈之间的交互变得越来越普遍。对于.NET应用程序来说,有时需要调用由Java开发的WebService。这种跨平台的服务...

    c#调用Java webService的专题(一)

    本文将深入探讨如何使用C#调用Java WebService,这是实现.NET与Java平台间互操作性的一个重要方式。我们将首先理解WebService的基本概念,然后详细讲解C#中如何通过.NET Framework的SOAP客户端代理类来调用Java ...

    PB调用JAVA WEBSERVICE实例

    标题中的“PB调用JAVA WEBSERVICE实例”指的是使用PowerBuilder(PB)应用程序调用由Java编写的Web服务。在企业级应用开发中,不同语言之间的互操作性是非常重要的,而Web服务提供了一种标准的方式来实现这一点。让...

    C#调用JavaWebService(客户端)

    本主题将深入探讨如何使用C#作为客户端来调用Java编写的WebService。WebSocket服务提供了平台无关的通信方式,使得不同编程语言间的数据交换变得可能。下面我们将详细讨论这个过程。 首先,了解WebService的基本...

    java调用webservice.zip

    java调用webservicejava调用webservice.zipjava调用webservice.zipjava调用webservice.zipjava调用webservice.zipjava调用webservice.zipjava调用webservice.zipjava调用webservice.zipjava调用webservice.zipjava...

    asp.net调用java webservice实例

    ### ASP.NET 调用 Java WebService 实例详解 #### 背景介绍 随着互联网技术的发展,跨平台、跨语言的服务交互变得越来越重要。Web Service 技术为不同编程环境之间的服务通信提供了一种标准的方式。本文将详细介绍...

    调用 java webservice 的问题

    调用Java WebService的问题在IT领域中颇为常见,尤其是在跨平台、跨语言的环境中,如C#调用Java WebService。以下将详细解析这一过程中的关键知识点,包括WebService的架构原理、工具选择(如Axis2)、数据类型转换...

    asp.net通过WebService调用Java接口全过程

    ASP.NET调用Java接口主要涉及的是跨平台的通信技术,其中关键步骤是通过WebService作为中间桥梁来实现。这里,我们详细解析整个过程: 1. **部署Java WebService**: - 使用Tomcat这样的应用服务器部署Java ...

    java调用C++ webservice

    本话题主要探讨如何使用Java调用由C++实现的Web服务(Webservice)。在给出的描述中,提到了通过WSDL(Web Services Description Language)文件来实现这一目标。以下是关于这个主题的详细知识点: 1. **Web服务...

    pb12.5调用java WebService

    为了帮助你更好地理解和实践,压缩包中的"PB调用WebService"文件很可能包含了一些示例代码或者截图,它们能更直观地展示上述步骤的具体实现。如果在实际操作中遇到任何困难,可以随时联系提供者以获取更多帮助。 总...

    C++ 调用javaWebService接口代码

    本主题聚焦于如何在C++中调用Java WebService接口,这涉及到两种编程语言的互操作性以及Web服务技术的理解。让我们深入探讨这个过程。 首先,我们需要理解什么是Java WebService。WebService是一种基于标准的、平台...

    C#调用java发布的WebService终稿.pdf

    C# 调用 Java 发布的 WebService 终稿 C# 调用 Java 发布的 WebService 是一种常见的跨语言通信方式。在本文中,我们将介绍如何使用 C# 调用 Java 发布的 WebService。 标题解释 C# 调用 Java 发布的 WebService ...

    java 调用 odi webservice

    Java 调用 ODI webservice 实现数据同步 Java 调用 ODI webservice 是实现数据同步的一种常见方式。ODI(Oracle Data Integrator)是一种数据集成平台,提供了webservice接口,允许用户通过webservice调用ODI方案...

    sap abap调用java生成的webservice手册

    【SAP ABAP调用Java生成的Web Service手册】 在SAP系统中,与外部服务进行交互时,经常需要调用由Java等其他语言编写的Web Service。本手册详细介绍了如何在MyEclipse环境中生成Web Service,并在SAP ABAP环境中...

    java调用json参数的webservice

    在探讨Java调用带有JSON参数的WebService之前,我们首先需要了解几个关键的技术概念:Java、JSON以及WebService。 Java是一种广泛使用的编程语言,它具有面向对象、跨平台、多线程以及健壮性等特点。Java在企业级...

    java android 调用webservice

    本篇将详细讲解如何在Android应用中使用Java调用Webservice。 一、理解Web服务 Web服务是一种基于互联网的、标准化的服务交互方式,它允许不同系统之间的应用程序共享数据和功能。常见的Web服务有SOAP(Simple ...

    JAVA 调用SAP SOAP webservice.docx

    JAVA 调用 SAP SOAP webservice 详解 在本文中,我们将详细介绍如何使用 JAVA 调用 SAP SOAP webservice,包括配置 SAP 登录信息、创建 java 项目、添加 web 服务客户端、生成 JAVA 类、调用接口等步骤。 配置 SAP...

    c#调用java带身份验证webservice

    本主题将深入探讨如何使用C#来调用带有身份验证的Java Web服务。Web服务作为一种基于标准的通信方式,允许不同语言和平台之间的应用程序共享数据和功能。在这个案例中,我们将重点关注C#与Java之间的交互,特别是...

Global site tag (gtag.js) - Google Analytics