How to Use Afnetworking or Sthttprequest to Make a Request of a Soap Web Service

How can you use AFNetworking or STHTTPRequest to make a request of a SOAP web service?

STHTTPRequest

//create request
STHTTPRequest *request = [STHTTPRequest requestWithURL:url];
//set header here
[request setHeaderWithName:@"Host" value:@"www.w3schools.com"];
[request setHeaderWithName:@"SOAPAction" value: @"http://www.w3schools.com/webservices/CelsiusToFahrenheit"];
[request setHeaderWithName:@"Content-Type" value:@"text/xml; charset=utf-8"];
//set body here
request.rawPOSTData = soapData;

//completion block
request.completionBlock = ^(NSDictionary *headers, NSString *body) {
NSLog(@"headers = %@\nbody = %@", headers, body);

//parse xml string object here as request is successfull
if (body.length > 0)
{
NSError *error= nil;
NSDictionary *dict = [XMLReader dictionaryForXMLString:body error:&error];
if (!error)
{
NSLog(@"XML Dictionary: %@",dict);
//do necessary requirement here
}
else
NSLog(@"Error while parsing xml data : %@",[error description]);

}
else
NSLog(@"No response from request");
};

//error block
request.errorBlock = ^(NSError *error) {
NSLog(@"%@",[error description]);
};

//start request
[request startAsynchronous];

AFNetworking

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:theRequest];

operation.responseSerializer = [AFXMLParserResponseSerializer serializer];

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

//parse NSXMLParser object here if request successfull
if ([responseObject isKindOfClass:[NSXMLParser class]]) {
NSXMLParser *parser = (NSXMLParser *)responseObject;
NSDictionary *dict = [XMLReader dictionaryForNSXMLParser:parser];
NSLog(@"JSON: %@ : %@", responseObject,dict);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:operation];

Here XMLReader provides NSDictionary of XMLData using NSXMLParser

I haved added one more method in XMLReader classes :

+(NSDictionary*)dictionaryForNSXMLParser:(NSXMLParser*)parser error:(NSError **)error

EDIT : Method Description

+ (NSDictionary *)dictionaryForNSXMLParser:(NSXMLParser *)xmlParser error:(NSError **)error
{
XMLReader *reader = [[XMLReader alloc] initWithError:error];
NSDictionary *rootDictionary = [reader objectWithNSXMLParser:xmlParser options:0];
return rootDictionary;
}

objectWithNSXMLParser method.

- (NSDictionary *)objectWithNSXMLParser:(NSXMLParser *)xmlParser options:(XMLReaderOptions)options
{
// Clear out any old data
self.dictionaryStack = [[NSMutableArray alloc] init];
self.textInProgress = [[NSMutableString alloc] init];

// Initialize the stack with a fresh dictionary
[self.dictionaryStack addObject:[NSMutableDictionary dictionary]];

[xmlParser setShouldProcessNamespaces:(options & XMLReaderOptionsProcessNamespaces)];
[xmlParser setShouldReportNamespacePrefixes:(options & XMLReaderOptionsReportNamespacePrefixes)];
[xmlParser setShouldResolveExternalEntities:(options & XMLReaderOptionsResolveExternalEntities)];

xmlParser.delegate = self;
BOOL success = [xmlParser parse];

// Return the stack's root dictionary on success
if (success)
{
NSDictionary *resultDict = [self.dictionaryStack objectAtIndex:0];
return resultDict;
}

return nil;
}

XMLReader Xcode Error

I was trying that code myself just a minute ago.

You have to add in XMLReader.h:

+(NSDictionary*)dictionaryForNSXMLParser:(NSXMLParser*)parser error:(NSError **)error;

Then in the XMLReader.m these two:

+ (NSDictionary *)dictionaryForNSXMLParser:(NSXMLParser *)xmlParser error:(NSError **)error
{
XMLReader *reader = [[XMLReader alloc] initWithError:error];
NSDictionary *rootDictionary = [reader objectWithNSXMLParser:xmlParser options:0];
return rootDictionary;
}
- (NSDictionary *)objectWithNSXMLParser:(NSXMLParser *)xmlParser options:(XMLReaderOptions)options
{
// Clear out any old data
self.dictionaryStack = [[NSMutableArray alloc] init];
self.textInProgress = [[NSMutableString alloc] init];

// Initialize the stack with a fresh dictionary
[self.dictionaryStack addObject:[NSMutableDictionary dictionary]];

[xmlParser setShouldProcessNamespaces:(options & XMLReaderOptionsProcessNamespaces)];
[xmlParser setShouldReportNamespacePrefixes:(options & XMLReaderOptionsReportNamespacePrefixes)];
[xmlParser setShouldResolveExternalEntities:(options & XMLReaderOptionsResolveExternalEntities)];

xmlParser.delegate = self;
BOOL success = [xmlParser parse];

// Return the stack's root dictionary on success
if (success)
{
NSDictionary *resultDict = [self.dictionaryStack objectAtIndex:0];
return resultDict;
}

return nil;
}

After that remember to import XMLReader.h and use the method. Notice that it has the error handling in it so if you copy pasted the code it's not same.

[XMLReader dictionaryForNSXMLParser:parser error:nil];

If it still doesn't work try cleaning the project with CMD+SHIFT+K and building it again.

iPhone: How to send a HTTP request to a web service using Xcode

Edit, because this is a popular question and time keeps going on.
In the meantime Apple introduced NSJSONSerialization. Have a look a the docs: https://developer.apple.com/documentation/foundation/jsonserialization
Only if you need to create code for iOS earlier than 5.0 you may want to use the json-framwork as mentioned below.

Besides that, the following original answer is still valid:

Assuming that you exchange your data in JSON, you may be interested in reading this.
http://iosdevelopertips.com/cocoa/json-framework-for-iphone-part-2.html

However, the first part of that article answers your more general question on how to receive data from a web server/service:

- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;

// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];

// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}

This is a simple example of a http request and surely good enough for your next steps.
This method is given a URL and it returns the data sent by the server in an NSString.

Once that is working properly you will like to avoid that your app freezes while the request is "on the air".
You can fix that by asynchronous requests. Google or the search on stackoverflow will provide you with links to examples and tutorials about that. But I suggest to go from here first, although this may not be the final solution.



Related Topics



Leave a reply



Submit