2011-11-29 128 views
1

我有一个关于xml调用REST Web服务的问题,我必须将以下参数传递给我的Web服务,格式如下:其他Web服务调用 - XML POST请求 - iPhone

http://XXX.XXX.XXX.XXX/gayanAPI/GayanRESTService.svc/login

enter image description here

所以我写this.But其做出一些错误代码。 (响应代码:400)我的示例代码如下;

//prepare request 
NSString *urlString = [NSString stringWithFormat:@"http://XXX.XXX.XXX.XXX/gayanAPI/GayanRESTService.svc/login"]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; 
[request setURL:[NSURL URLWithString:urlString]]; 
[request setHTTPMethod:@"POST"]; 

//set headers 
NSString *contentType = [NSString stringWithFormat:@"application/xml"]; 
[request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

//create the body 
NSMutableData *postBody = [NSMutableData data]; 
[postBody appendData:[[NSString stringWithFormat:@"<Login xmlns="">"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"<UserId>%@</UserId>",@"200"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"<PassWord>%@</PassWord>",@"123"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"<ResId>%@</ResId>",@"1000"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"<DeviceId>%@</DeviceId>",@"1234"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"</Login>"] dataUsingEncoding:NSUTF8StringEncoding]]; 

//post 
[request setHTTPBody:postBody]; 

//get response 
NSHTTPURLResponse* urlResponse = nil; 
NSError *error = [[NSError alloc] init]; 
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; 
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
NSLog(@"Response Code: %d", [urlResponse statusCode]); 
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) { 
    NSLog(@"Response: %@", result); 
    //here you get the response 
} 

它是什么原因。我在创建XML请求时犯了一个错误。请帮我解决这个问题?你能给我一个这样的代码吗?我厌倦了这一点。

非常感谢。

回答

1

在这一行,

[postBody appendData:[[NSString stringWithFormat:@"<Login xmlns="">"] dataUsingEncoding:NSUTF8StringEncoding]]; 

你需要用反斜杠引用双引号(“)(\),如下所示:

[postBody appendData:[[NSString stringWithFormat:@"<Login xmlns=\"\">"] dataUsingEncoding:NSUTF8StringEncoding]]; 

我不知道它是否会引起错误,虽然

+0

是的,非常感谢。:) –