2

我对 Objective-C 非常陌生,并且在某一点上感到震惊。我必须发布 XML 请求以休息服务 url 并从中获取响应。我正在使用 NSMutableRequest。但看不到任何响应。不明白在哪里我错了……

请求 XML 是这样的:

<GetUserRequest xmlns="http://schemas.datacontract.org/2004/07/DModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ID>456789</ID>
<UserEmail>John@yahoo.com</UserEmail>
</GetUserRequest>

My url is like this : http://192.158.0.104:8732/IServices/GetXml

我的代码是这样的:

NSString *urlString1=[NSString stringWithFormat:@"http://192.158.0.104:8732/IServices/GetXml"];
NSMutableURLRequest *request=[[[NSMutableURLRequest alloc] init]autorelease];
[request setURL:[NSURL URLWithString:urlString1]];
[request setHTTPMethod:@"POST"];
NSString *contentType=[NSString stringWithFormat:@"application/xml"];
[request addValue:contentType  forHTTPHeaderField:@"Content-type"];

NSMutableData *postBody=[NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"<GetUserRequest xmlns=\"http://schemas.datacontract.org/2004/07/DModel\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"]dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"<ID>456789</ID>"]dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"<UserEmail>John@yahoo.com</UserEmail>"]dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"/GetUserRequest>"]dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
NSHTTPURLResponse *urlResponse=nil;
NSError *error=[[NSError alloc]init];
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *rss=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding ];
NSlog(@"Response Code:%d",[urlResponse statusCode]);
if([urlResponse statusCode ]>=200 && [urlResponse statusCode]<300)
{
    NSLog(@"Response:%@",rss);
}

但我在活动控制台中看不到任何东西......

任何帮助,将不胜感激 ...

4

1 回答 1

0

该代码对我来说看起来很糟糕,并且没有包含足够的错误检查([NSURLConnection sendSynchronousRequest]可以nil在发生错误时返回)。将结尾修改为:

NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request 
                                             returningResponse:&urlResponse 
                                                         error:&error];
if (responseData != nil)
{
    NSString *rss = [[NSString alloc] initWithData:responseData 
                                          encoding:NSUTF8StringEncoding ];
    NSlog(@"Response Code:%d",[urlResponse statusCode]);
    if([urlResponse statusCode ]>=200 && [urlResponse statusCode]<300)
    {
        NSLog(@"Response:%@",rss);
    } 
}
else
{
    NSLog(@"Failed to send request: %@", [error localizedDescription]);
}
于 2012-10-16T11:10:00.233 回答