2009-08-17 66 views
13

我必须开发一个应用程序,它将请求ASP.NET中开发的Web服务。iPhone与ASP.NET WebService的交互

我不知道,什么是创建到asp.net web服务的请求的代码,

如何asp.net web服务会以iPhone应用程序应对?

iPhone如何以正确的方式解析该响应?

我已经阅读了这个问题


How to Fetch Data From a WebService in iPhone?
但给定链路只给出了.pdf文件。

我的需求是示例代码 - 可以解释我如何进行连接&从asp.net web服务检索数据。

回答

20

你实际上可以制作一个网络服务,并使其真正容易地集成到你的iphone。我建议如果你使用.net创建一个带有webHttp出价的WCF服务并实现get和post方法,你可以在json和xml中获得响应(这是一组解析JSON的类,它将解析响应轻而易举,它们在网络中可用),只需使用NSURLRequest就可以执行从iphone获取和发布的小设置。这里有一篇文章谈论如何制作一个宁静的wcf服务http://www.developer.com/net/article.php/10916_3695436_2。它也很容易使用WCF为您的服务添加身份验证和安全性。

+0

我有我自己的WCF服务正在运行,我不使用soap tho – Daniel 2009-08-18 17:25:10

+1

我强烈地同意你的意见,肥皂协议太大了Iphone – fyasar 2009-11-02 11:55:38

+0

兄弟,你提供的链接不再可用。发布新的,如果你有。 – 2013-06-04 06:09:46

1

如果你在两边都没有与ASP.NET集成,我可能会特别避免使用“Web服务”,只输出你自己的XML格式,并在iPhone端用XML库适当地处理它。

3
- (void)viewDidLoad { 
[super viewDidLoad]; 

// create a soap Message which is given in your required web service 

NSString *[email protected]"<?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/\">\n" 
"<soap:Body>\n" 
"<GetCategory xmlns=\"http://tempuri.org/\" />\n" 
"</soap:Body>\n" 
"</soap:Envelope>"; 

// create a url to your asp.net web service. 
NSURL *tmpURl=[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.32.10/Itavema/Admin/Itavema_Service.asmx"]]; 

// create a request to your asp.net web service. 
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:tmpURl]; 

// add http content type - to your request 
[theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

// add SOAPAction - webMethod that is going to be called 
[theRequest addValue:@"http://tempuri.org/GetCategory" forHTTPHeaderField:@"SOAPAction"]; 

// count your soap message lenght - which is required to be added in your request 
NSString *msgLength=[NSString stringWithFormat:@"%i",[soapMessage length]]; 
// add content length 
[theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"]; 

// set method - post 
[theRequest setHTTPMethod:@"POST"]; 

// set http request - body 
[theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]]; 

// establish connection with your request & here delegate is self, so you need to implement connection's methods 
NSURLConnection *con=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

// if connection is established 
if(con) 
{ 
    myWebData=[[NSMutableData data] retain]; 
    // here -> NSMutableData *myWebData; -> declared in .h file 
} 
} 

// a method when connection receives response from asp.net web server 
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
[myWebData setLength: 0]; 
} 
// when web-service sends data to iPhone 
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
[myWebData appendData:data]; 
} 
// when there is some error with web service 
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
[connection release]; 
} 
// when connection successfully finishes 
-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
// check out your web-service retrieved data on log screen 
NSString *theXML = [[NSString alloc] initWithBytes: [myWebData mutableBytes] length:[myWebData length] encoding:NSUTF8StringEncoding]; 
NSLog(@"%@",theXML); 
[theXML release]; 

// if parser isn't nil. here NSXMLParser *myXMLParser; in .h file 
if(myXMLParser) 
{ 
    [myXMLParser release]; 
} 

// supply your responded data to xmlParser - xmlParser will parse xmlData & then you can use it 
myXMLParser = [[NSXMLParser alloc] initWithData: myWebData]; 

// here delegate self means implement xmlParse methods 
[myXMLParser setDelegate: self]; 

[myXMLParser setShouldResolveExternalEntities: YES]; 

// parse method - will invoke xmlParserMethods 
[myXMLParser parse]; 
[connection release]; 
[myWebData release]; 
} 


//#pragma mark xmlParser 
// suppose <myDataTag>myData</endmyDataTag> is the xmlData 
// this function will read "<myDataTag>" & tag attributes 
-(void)parser:(NSXMLParser*)parser 
          didStartElement:(NSString*)elementName 
          namespaceURI:(NSString*)namespaceURI 
          qualifiedName:(NSString*)qualifiedName 
          attributes:(NSDictionary*)attributeDict 
{ 
    if([elementName isEqualToString:@"GetCategoryResult"]) 
    { 
     // here categoryArray is NSMutable array declared in .h file. 
     // init your array when root element/document element is found 
     CategoryArray=[[NSMutableArray alloc]init]; 
    } 
    else if([elementName isEqualToString:@"Prop_Category"]) 
    { 
     aCategory=[[Category alloc] init]; 
     // if a tag has attribues like <myDataTag id="sagar"> 
     //aCategory.ID=[attributeDict objectForKey:@"id"]; 
    } 
} 

// suppose <myDataTag>myData</endmyDataTag> is the xmlData 
// this function will read "myData" & tag attributes 
-(void)parser:(NSXMLParser*)parser 
          foundCharacters:(NSString*)string 
{ 
    // here currentElementValue is an NSMutableString declared in .h file 
    // store read characters in that mutable string & then add to your object. 
    if(!currentElementValue) 
    { 
     currentElementValue=[[NSMutableString alloc] initWithString:string]; 
    } 
    else 
    { 
     [currentElementValue appendString:string]; 
    } 
} 

// suppose <myDataTag>myData</endmyDataTag> is the xmlData 
// this function will read "</endmyDataTag>" & tag attributes 
-(void)parser:(NSXMLParser*)parser 
      didEndElement:(NSString*)elementName 
      namespaceURI:(NSString*)namespaceURI 
      qualifiedName:(NSString*)qualifiedName 
{ 
    if([elementName isEqualToString:@"GetCategoryResult"]) 
    { 
     // if end of root element is found- i.e. end of your xml file. 
     return; 
    } 
    else if([elementName isEqualToString:@"Prop_Category"]) 
    { 
     // end of a single data element 
     // suppose <category> 
     //    <id>10</id> 
     //    <name><sagar></name> 
     //   </category> 
     // when we found </category> we have finished entire category object. 
     // here we have an object aCategory -> created custom class "Category" 
     // CategoryClass -> NSString *name; NSInteger id; 
     // Note: "important" 
     //->class variables must be same as tag 

     // now after reading entire object add to your mutable array 
     // now this mutable array can be used for Table, UIPicker 
     [CategoryArray addObject:aCategory]; 
     [aCategory release]; 
     aCategory=nil; 
     [CategoryTable reloadData]; 
    } 
    else 
    { 
     // which is equivalent to aCategory.id=10 & [email protected]"sagar" 
     [aCategory setValue:currentElementValue forKey:elementName]; 

     // remove previously read data 
     [currentElementValue release]; 
     currentElementValue=nil; 
    } 
} 
3

Hessian比XML更好的通信协议。作为一种二进制格式,它甚至更加紧凑,并且使用严格的格式解析是更快的

作为奖励,已经有Java,.NET和PHP公开Web服务的框架。真的很容易。 Asume你有这样的C#接口:

public interface ITest { 
    public string getGreeting(); 
    int addNumbers(int a, int b); 
} 

然后实现它使用HessianC#在服务器上是一个单元:

public class CTest:CHessianHandler, ITest { 
    public string getGreeting() { return "Hello World!"; } 
    public int addNumbers(int a, int b) { return a + b; } 
    [STAThread] 
    private static void Main(string[] args) { 
    CWebServer web = new CWebServer(5667, "/test/test.hessian", typeof (CTest)); 
    web.Paranoid = true; 
    web.AcceptClient("[\\d\\s]"); 
    web.Run(); 
    for (;;) { 
     if (Console.ReadLine() != "") { 
     web.Stop(); 
     break; 
     } 
    } 
    } 
} 

在iPhone上侧的C#接口需要被翻译成Objective-C的协议:

@protocol ITest 
-(NSString*)getGreeting; 
-(int)addNumbers:(int)a :(int)b; 
@end 

,然后使用HessianKit用于获取代理的服务几乎是一样容易:

id<ITest> proxy = [CWHessianConnection proxyWithURL:serviceURL 
              protocol:@protocol(ITest)]; 
NSLog(@"Greeting: %@", [proxy getGreeting]); 
NSLog(@"The answer: %d", [proxy addNumbers:40 :2]); 

在这个简短的回答中,方法名称并不完全是C#-ish,也不完全是Obj-C-ish。这是因为默认情况下HessianKit使用Java的命名约定。这可以通过提供方法和类型名称转换在HessianKit中重写。因此,连接上的C#和Obj-C端在家中感觉都是100%。例如:

[CWHessianArchiver setClassName:@"com.mycompany.ITest" 
        forProtocol:@protocol(CWTest)]; 
[CWHessianArchiver setMethodName:@"AddNumbers" 
        forSelector:@selector(addInt:toInt:)]; 
0

尝试WCF哥们,它允许你创建easilly一个SOAP web服务,你可以从任何地方

1

这个答案是过时的电话,但对协议的缘故:

我已经使用sudzc.com将我的web服务转换为Objective-C类。

它工作得很好,并且极大地简化了事情。

干杯, Oded。