我成功地从 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 文档,而现在不一定要解析该文档。
提前感谢所有回复的人。