2

我成功地从 iOS 连接到 .NET Web 服务,并通过 NSLog 将响应 xml 文档打印到控制台。这是我通过 AFNetworking 库进行的。我现在可以通过 NSURLConnection 连接到同一个 Web 服务,但是,我无法提取保存在 NSMutableData 对象中的 xml 文档。AFNetworking 库能够自动执行此操作,这使事情变得更容易,但我想知道如何使用本机 iOS 库来执行此操作。这是我正在使用的代码:

//This is the code I am using to make the connection to the web service
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPBody:[soapBody dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPMethod:@"POST"];

    [request addValue:@"http://tempuri.org/Customers" forHTTPHeaderField:@"SOAPAction"];
    [request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    // Convert your data and set your request's HTTPBody property
    NSString *stringData = @"some data";
    NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBodyData;

    // Create url connection and fire request
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [conn start];

这是我必须从 Web 服务接收数据的代码:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    NSString *strData = [[NSString alloc]initWithData:_responseData encoding:NSUTF8StringEncoding];

    NSLog(@"%@", strData);

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!

}


/*
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"%@", [operation responseString]);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"failed");

    }];

    [operation start];
    */

我只是想打印出我收到的整个 xml 文档,而现在不一定要解析该文档。

提前感谢所有回复的人。

4

1 回答 1

0

查看服务器上的帮助文档,它提出了一个示例请求:

<?xml version="1.0" encoding="utf-8"?>
<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/">
  <soap:Body>
    <Customers xmlns="http://tempuri.org/" />
  </soap:Body>
</soap:Envelope>

因此,我将该示例请求放在一个文本文件中,并通过NSURLConnection如下方式发起请求:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSString *filename = [[NSBundle mainBundle] pathForResource:@"soap1-1example" ofType:@"xml"];
NSData *requestBodyData = [NSData dataWithContentsOfFile:filename];
request.HTTPBody = requestBodyData;

[request setHTTPMethod:@"POST"];

[request addValue:@"http://tempuri.org/Customers" forHTTPHeaderField:@"SOAPAction"];
[request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

[NSURLConnection connectionWithRequest:request delegate:self];

请注意,我没有调用start,因为正如文档所述,除非您使用“initWithRequest:delegate:startImmediately:方法并提供NO参数startImmediately”,否则它将自动为您启动。实际上,您的原始代码启动了两次连接,这可能会出现问题。

无论如何,将我修改后的代码与上述请求一起使用,它运行良好,同时NSURLConnection使用AFNetworking. 我得到的回应(美化)是:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
    <CustomersResponse xmlns="http://tempuri.org/">
    <CustomersResult>
        <Customer>
            <FirstName>Mohammad</FirstName>
            <LastName>Azam</LastName>
        </Customer>
        <Customer>
            <FirstName>John</FirstName>
            <LastName>Doe</LastName>
        </Customer>
    </CustomersResult>
</CustomersResponse>
</soap:Body>
</soap:Envelope>

如果它仍然不适合您,也许您可​​以分享您提交的请求的详细信息。


顺便说一句,由于这里不需要委托方法(例如,您没有进行流式传输,您没有进行任何身份验证等),因此您可以消除所有NSURLConnectionDataDelegate方法(didReceiveResponse,didReceiveData等),而只需使用NSURLConnectionclass方法,sendAsynchronousRequest(在 iOS 5 及更高版本中):

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSString *filename = [[NSBundle mainBundle] pathForResource:@"soap1-1example" ofType:@"xml"];
NSData *requestBodyData = [NSData dataWithContentsOfFile:filename];
NSAssert(requestBodyData, @"requestBodyData is nil!");
request.HTTPBody = requestBodyData;

[request setHTTPMethod:@"POST"];

[request addValue:@"http://tempuri.org/Customers" forHTTPHeaderField:@"SOAPAction"];
[request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

if (!self.networkQueue)
{
    self.networkQueue = [[NSOperationQueue alloc] init];
    self.networkQueue.name = @"com.yourdomain.yourapp.networkQueue";
}

[NSURLConnection sendAsynchronousRequest:request
                                   queue:self.networkQueue
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                           if (!error)
                           {
                               NSString *string = [[NSString alloc] initWithData:data
                                                                        encoding:NSUTF8StringEncoding];

                               NSLog(@"%s: data=%@", __FUNCTION__, string);
                           }
                           else
                           {
                               NSLog(@"%s: error=%@", __FUNCTION__, error);
                           }
                       }];
于 2013-05-01T17:26:59.460 回答