我有一个关于xml调用REST Web服务的问题,我必须以下列格式将以下参数传递给我的Web服务;
http://XXX.XXX.XXX.XXX/gayanAPI/GayanRESTService.svc/login
所以我为此编写了一个代码。但它的make有些错误。 (响应代码: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请求时犯了一个错误。请帮帮我解决这个问题?你能给我一个代码吗?我厌倦了这一点。
非常感谢。
答案 0 :(得分:1)
在这一行中,
[postBody appendData:[[NSString stringWithFormat:@"<Login xmlns="">"] dataUsingEncoding:NSUTF8StringEncoding]];
您需要使用反斜杠(\)引用双引号(“),如下所示:
[postBody appendData:[[NSString stringWithFormat:@"<Login xmlns=\"\">"] dataUsingEncoding:NSUTF8StringEncoding]];
但我不确定它是否会导致错误。