从iPhone发送对XML'服务URL的XML请求

时间:2012-10-15 09:40:34

标签: xcode4 http-post

我对Objective-C非常陌生,并且在某一点上已经被攻击。我必须POST XML请求来休息服务url并从中获取响应。我使用NSMutableRequest.But看不到任何响应.Couldn'我明白我哪里出错......

请求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);
}

但我无法在主动控制台中看到任何内容......

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

1 个答案:

答案 0 :(得分: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]);
}