iOS: Accessing wsdl service api from iOS client - ios

I have a web service created through Eclipse. Created a web service method and wsdl for that class. I would like to know how can i access this web service api from my iOS client? For ex: my wsdl file is 'ReceiverClass.wsdl' and 'ReceiverClass.java class contains a method called 'RespondResult(..)'. I know about NSURLConnection, i'm asking how can i point to this url api?
Thank you!
Getsy.

You'll need a SOAP framework. There's not one built into iOS, but here's one which was the first hit on Github: https://github.com/priore/SOAPEngine.

You can use this iPhone Web Services Client. Also can refer to these tutorials.
SOAP Based Web Services Made Easy On The iOS Platform
Working with iOS and SOAP

There is no easy solution, easiest one is to move away from SOAP.
Meanwhile you can try http://sudzc.com/ or you can write a simple wrapper yourself which will send and receive XML packets.
In example below, I observed the xml packets through "Poster" firefox plugin and made generic methods to make SOAP request. The biggest drawback is that I'm ignoring WSDL and I have to implement each method myself (unlike Java).
- (void) requestData:(NSString *) request withParameters:(NSDictionary*)parameters
soapAction:(NSString*)soapAction serviceName:(NSString *)url
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
NSString *packet = [self formatRequest:request WithParameters:parameters];
NSData *envelope = [packet dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request1 setHTTPMethod:#"POST"];
[request1 setHTTPBody:envelope];
[request1 setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
AFHTTPRequestOperation * operation = [[AFHTTPRequestOperationManager manager] HTTPRequestOperationWithRequest:request1 success:success failure:failure];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
[[NSOperationQueue mainQueue] addOperation:operation];
}
- (NSString*) formatRequest:(NSString*)request WithParameters:(NSDictionary *)parameters
{
NSMutableString *packet = [[NSMutableString alloc] init];
[packet appendString:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
"<soap12:Body>"];
[packet appendFormat:#"<%# xmlns=\"http://tempuri.org/\">",request];
for (NSString *key in parameters) {
[packet appendFormat:#"<%#>%#</%#>",key,[parameters objectForKey:key],key];
}
[packet appendFormat:#"</%#>",request];
[packet appendString:#"</soap12:Body></soap12:Envelope>"];
return packet;
}

Related

About web service Json/rest api/Nsurl connection

I am starting learning about web service, where I use one url api to get data and to display in my table view. But I saw some tutorials - in that they use NSURLConnection or Rest API or AFNetworking.
I am really confused about all type. Which one should I use in that above type. For web service which type should I use. And also I saw some doubts in SO that use synchronous or asynchronous. Thus this any another type to get data from URL?
Actually for all web service, which should I use to get data and display?
-(void)JsonDataParsing
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *jsonDict = (NSDictionary *) responseObject;
//!!! here is answer (parsed from mapped JSON: {"result":"STRING"}) ->
NSString *res = [NSString stringWithFormat:#"%#", [jsonDict objectForKey:#"result"]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//....
}
];
}
Firstly, AFNetworking and NSURLConnection are used on Mobile Side.
Rest API is not from mobile side. Rest API you implemented on server side which handle CRUD operations like GET, POST, PUT and DELETE.
Third party libraries are there to ease our work. And AFNetworking is very popular and trustworthy library.
AFNetworking makes asynchronous network requests. To read more about it, visit Introduction to AFNetworking.
AFNetworking does everything NSURLConnection can. Using it now will save you a lot of time writing boilerplate code!
NSURLConnection and NSURLSession is apple API use to manage network operation like download and upload, AFNetworking is the framework that use those 2 API and added multithreading/error handling/network reachability....to make your life easier, RESTful is the architecture for client-server connecting, u can implement it in your serverside to return things back to your clientside in easy to use model (JSON).
synchronous mean u wait for it to complete to do anything else, asynchronous means u just start it but don't need to wait for it, like u do a request to server and user still can interact with your UI at the same time, so its advised that use asynchronous task to request to server then only update the UI in synchronous
hope my explain is easy to understand and correct :)
NSURLConnection
This lets you to load the content of URL by providing the URL request object. By using NSURLConnection you can load URL requests both asynchronously using a callback block and synchronously. See this example
NSURL *URL = [NSURL URLWithString:#"http://example.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// ...
}];
For more you can go to apple docs
AFNetworking
This is third party library built on the top of Foundation URL Loading.
This is very easy to install through pods and handy to use. See below example like how I am using the same in my app
-(AFHTTPRequestOperationManager *)manager
{
if (!_manager)
{
_manager = [AFHTTPRequestOperationManager manager];
_manager.requestSerializer = [AFHTTPRequestSerializer serializer];
_manager.responseSerializer = [AFHTTPResponseSerializer serializer];
}
return _manager;
}
Above we are initializing the instance of AFHTTPRequestOperationManager *manager
[self.manager POST:#"http://example.com" parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error;
NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
// return response dictionary in success block
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
// return error in failure block
}]
Above method will load data asynchronously and remaining is self explanatory. But if you want to block the user interface like a synchronous request than use [operation waitUntilFinished] which is an anti-pattern. Here operation is a instance of AFJSONRequestOperation.

Upgrading to AFNetworking

I am taking over an old iOS project from developers no longer part of the project - the app is getting a rewrite and with that I am going to support iOS7 and upwards only.
So, I wanted to use AFNetworking 2.0 instead of ASIHTTPRequest - the reason behind this is NSURLSeesion. AFNetworking 2.0 supports NSURLSession and with that I can get my app to download content in the background at opportunistic times (According to Apple - NSURLSession must be used and Background Fetch mode turned on, for this to work? )
Let me start out by saying I am a new developer to iOS and networking stuff goes a little over my head - but I am determined to learn more about it and as much as I can. I have read AFNetworking documentation as well, but I fear since some of the terminology escapes me (Request, Response, Sterilisation, etc) - I am not grasping them 100%.
So, I took a look at the ASIHTTPRequest code the previous developer used to, from what I can see, build a GET / POST request - This is the code they used:
+ (ASIHTTPRequest*) buildRequest: (NSString*) url RequestType: (NSString*) requestType
PostData: (NSString*) postData
Host: (NSString*) host
ContentType: (NSString*) contentType
SoapAction: (NSString*) soapAction
RequestProperties: (NSDictionary*) requestProperties
{
NSURL *url = [NSURL URLWithString: url];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:u] autorelease];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
[request setTimeOutSeconds:20];
[request setQueuePriority:NSOperationQueuePriorityVeryHigh];
if (host != nil)
[request addRequestHeader: #"Host" value: host];
if (contentType != nil)
[request addRequestHeader: #"Content-Type" value: contentType];
if (soapAction != nil)
[request addRequestHeader: #"SOAPAction" value:soapAction];
if (requestType != nil)
[request setRequestMethod: requestType];
if (postData != nil)
{
NSMutableData* mPostData = [NSMutableData dataWithData:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSString *msgLength = [NSString stringWithFormat:#"%d", [postData length]];
[request setPostBody: mPostData];
[request addRequestHeader: #"Content-Length" value:msgLength];
}
if (requestProperties != nil)
{
for (int i = 0; i < [[requestProperties allKeys] count]; i++)
{
[request addRequestHeader:[[requestProperties allKeys] objectAtIndex: i] value: [requestProperties objectForKey:[[requestProperties allKeys] objectAtIndex: i]]];
}
}
return request;
}
I'm trying to understand this code and upgrade it to use AFNetworking V2.0 instead. I assume, just replacing ASIHTTPRequest with AFHTTPRequestOperation will not do the trick, correct?
I have been given some help and also managed to do a lot of digging around to see how I can get this right.
I made the method simpler - as I did not need Soap / Content-type, etc - just urlParamerters and some basic stuff:
This is the answer I came up with:
+ (AFHTTPSessionManager *) buildRequest: (NSString*) url RequestType: (NSString*) requestType PostDataValuesAndKeys: (NSDictionary*) postData RequestProperties: (NSDictionary*) requestProperties
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
if ([requestType isEqualToString:#"GET"])
{
[manager GET:url parameters:postData success:^(NSURLSessionDataTask *dataTask, id responseObject){
//Success
NSLog (#"Success");
NSData *xmlData = responseObject;
NSLog(#"Got XML Data: %#", xmlData);
}
failure:^(NSURLSessionDataTask *dataTask, NSError *error){
//Failure
NSLog (#"Failure");
}];
}else if ([requestType isEqualToString:#"GT"]){
[manager POST:url parameters:postData success:^(NSURLSessionDataTask *dataTask, id responseObject){
//Success
}
failure:^(NSURLSessionDataTask *dataTask, NSError *error){
//Failure
NSLog (#"Failure");
}];
}
return manager;
}
It will work for what I need it to do - but I am not sure if it's the best way to do it.
I couldn't see how I could detect the requestType other thank with looking at the NSString value. I looked into the AFHTTPSessionManager.h file for some clues on what to do with that - Matt suggests overriding the GET / POST methods if I want them done differently - per his comments in the header file:
Methods to Override
To change the behavior of all data task operation construction, which
is also used in the GET / POST / et al. convenience methods,
override dataTaskWithRequest:completionHandler:.
Also there is a requestSerializer property in that file - which you could use to detect the type of request - however it's implementation goes to the super class: AFURLSessionManager
In that class - there is a requestWithMethodmethod.
So, I tried to do this instead:
If I try implement that method - then I am not using the convince methods in AFHTTPSessionManager:
(NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(NSDictionary *)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
Unless I have that completely wrong. After that I decided to just check the requestType using [NSString isEqualToString]

How to add an Auth Token in every request using AFIncrementalStore?

I have an iOS + Rails 3.1 app, and I'm using AFIncrementalStore for the client-server communication.
I have implemented Token Authentication on my Rails server according to this tutorial: http://matteomelani.wordpress.com/2011/10/17/authentication-for-mobile-devices/
I now want to include the &auth_token=XXXXXXXX in every request from client to server, including POST requests. How would I do that? I haven't found the solution in this related post: Using AFIncrementalStore with an Auth token
UPDATE: this is my first code attempt, but doesn't seem to send the auth_token:
(inside my AFIncrementalStoreHTTPClient sub-class)
- (NSMutableURLRequest *)requestForFetchRequest:(NSFetchRequest *)fetchRequest withContext:(NSManagedObjectContext *)context {
NSMutableURLRequest *request = [[super requestForFetchRequest:fetchRequest withContext:context] mutableCopy];
NSMutableString *requestBody = [[NSMutableString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding];
[requestBody appendFormat:#"&%#=%#", #"auth_token", #"xkT2eqqdoNp5y4vQy7xA"];
[request setHTTPBody:[requestBody dataUsingEncoding:NSUTF8StringEncoding]];
return request;
}
UPDATE: I skimmed your question (sorry!), and my sample code below works for a regular AFHTTPClient, but not AFIncrementalStore. The same basic approach will work, though, and there's sample code at this answer that should point you in the right direction.
You can't just append &auth_token=whatever to the end of your HTTP body in all cases.
You probably want to override your getPath... and postPath... methods with something like:
- (void)getPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
if (parameters) {
// Make a mutable copy and add the "token" parameter to the dictionary
NSMutableDictionary *mutableParams = [parameters mutableCopy];
[mutableParams setObject:#"whatever" forKey:#"token"];
parameters = [NSDictionary dictionaryWithDictionary:mutableParams];
} else {
parameters = #{#"token" : #"whatever"};
}
[super getPath:path parameters:parameters success:success failure:failure];
}
This approach will allow AFNetworking to appropriately encode your parameters depending on your specific request and encoding settings.
If you are rolling your own AFHTTPRequestOperation objects instead of using the convenience methods (you probably aren't), just make sure you include the token in parameters before you create your NSURLRequest like so:
NSURLRequest *request = [self requestWithMethod:#"GET" path:path parameters:parameters];

AFNetworking with GDataXML as HTTPBody for XML-RPC API

I am attempting to use AFNetworking with an XML-RPC based API while using GDataXML as my XML parsing and creation class.
I have successfully written some methods that output a proper XML request according to the spec of the API, I have also tested this XML request using apigee console and verified I get a correct response back every time with the apigee console and the API.
Now comes AFNetworking, I have the following code written which sometimes, but rarely works.
NSMutableURLRequest *request = [[FZAPIClient sharedClient] requestForDataServiceQueryOnTable:#"Contact" usingQueryData:#{ #"LastName" : #"Wagner" } forFields:#[ #"FirstName", #"LastName" ] withLimit:1000 forPage:0];
AFHTTPRequestOperation *operation = [[FZAPIClient sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error = nil;
GDataXMLDocument *opdoc = [[GDataXMLDocument alloc] initWithData:[[operation request] HTTPBody] options:0 error:&error];
if (error) {
NSLog(#"Error creating XML: %#", error);
}
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseObject options:0 error:nil];
GDataXMLElement *element = [doc rootElement];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[FZAPIErrorHandler handleError:error];
}];
[operation start];
Implementation for - (NSMutableURLRequest *)requestForDataServiceQueryOnTable:(NSString *)table usingQueryData:(NSDictionary *)queryData forFields:(NSArray *)fields withLimit:(NSInteger)limit forPage:(NSInteger)page;
- (NSMutableURLRequest *)requestForDataServiceQueryOnTable:(NSString *)table
usingQueryData:(NSDictionary *)queryData
forFields:(NSArray *)fields
withLimit:(NSInteger)limit
forPage:(NSInteger)page {
GDataXMLDocument *xmlDocument = [FZXMLGenerator requestForDataServiceQueryOnTable:table
usingQueryData:queryData
forFields:fields
withLimit:limit
forPage:page];
NSMutableURLRequest *request = [self requestWithMethod:#"POST" path:#"" parameters:nil];
[request setHTTPBody:[xmlDocument XMLData]];
[request setHTTPMethod:#"POST"];
return request;
}
When the request works, I get an excepted response.
When the request doesn't work (which is 99% of the time) I get the following response.
<?xml version="1.0" encoding="UTF-8"?>
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value>
<i4>0</i4>
</value>
</member>
<member>
<name>faultString</name>
<value>Failed to parse XML-RPC request: Premature end of file.</value>
</member>
</struct>
</value>
</fault>
</methodResponse>
This makes me suspect something is happening to the HTTPBody property, I have added logging just about everywhere I can think and see that the XML is indeed attached to the request when it is fired. It is also still accessible via the operation in the completion block.
Any ideas?
It looks like it was as simple as setting the content type on the request.
Updating the method to
- (NSMutableURLRequest *)requestForDataServiceQueryOnTable:(NSString *)table
usingQueryData:(NSDictionary *)queryData
forFields:(NSArray *)fields
withLimit:(NSInteger)limit
forPage:(NSInteger)page {
GDataXMLDocument *xmlDocument = [FZXMLGenerator requestForDataServiceQueryOnTable:table
usingQueryData:queryData
forFields:fields
withLimit:limit
forPage:page];
NSMutableURLRequest *request = [self requestWithMethod:#"POST" path:#"" parameters:nil];
[request setHTTPBody:[xmlDocument XMLData]];
[request setValue:#"application/xml" forHTTPHeaderField:#"Content-Type"];
return request;
}
Solved the problem, notice the line
[request setValue:#"application/xml" forHTTPHeaderField:#"Content-Type"];
To make this global on all requests I added the line, [self setDefaultHeader:#"Content-Type" value:#"application/xml"]; to my - (id)initWithBaseURL:(NSURL *)url; implementation.

OAuth 2 bearer Authorization header

With an update to the client's API the HTTPBasicAuthication method has been replace with a OAuth2 Bearer Authorization header.
With the old API I would do the following:
NSURLCredential *credential = [NSURLCredential credentialWithUser:self.account.username
password:self.account.token
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *space = [[NSURLProtectionSpace alloc] initWithHost:kAPIHost
port:443
protocol:NSURLProtectionSpaceHTTPS
realm:#"my-api"
authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
But this will not work with the Bearer header.
Now normally I would just add the header my self by adding it like so:
NSString *authorization = [NSString stringWithFormat:#"Bearer %#",self.account.token];
[urlRequest setValue:authorization forHTTPHeaderField:#"Authorization"];
But the problem with this solutions is that the API redirect most of the calls to other URLs, this has to do with security.
After the NSURLRequest gets redirected the Authorization header is removed from the request and since I'm unable to add the Bearer method to the NSURLCredentialStorage it can't authenticate any more after being redirected.
What would be a good solutions? I can only think to catch the redirect and modify the NSURLRequest so it does include the Bearer header. But how?
Well after much research I found out that I will just have to replace the NSURLRequest when a call is redirected.
Not as nice as I would like it to be, but is does work.
I used AFNetworking and added the redirect block, then check wether the Authorization header is still set if not I create a new NSMutableURLRequest and set all the properties to match the old request (I know I could have just created a mutable copy):
[requestOperation setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) {
if ([request.allHTTPHeaderFields objectForKey:#"Authorization"] != nil) {
return request;
}
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:request.URL cachePolicy:request.cachePolicy timeoutInterval:request.timeoutInterval];
NSString *authValue = [NSString stringWithFormat:#"Bearer %#", self.account.token];
[urlRequest setValue:authValue forHTTPHeaderField:#"Authorization"];
return urlRequest;
}];
I'm using AFNetworking Library
Find AFHttpClient.m and you have a method
- (void)setAuthorizationHeaderWithToken:(NSString *)token {
[self setDefaultHeader:#"Authorization" value:[NSString stringWithFormat:#"Token token=\"%#\"", token]];
}
replace this method with the following or if you need it for back compatibility keep it an add with a different name and use that name
- (void)setAuthorizationHeaderWithToken:(NSString *)token {
[self setDefaultHeader:#"Authorization" value:[NSString stringWithFormat:#"Bearer %#", token]];
}
then make the request with oauth access token. (Following is a GET method service)
NSURL *url = [EFServiceUrlProvider getServiceUrlForMethod:methodName];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setAuthorizationHeaderWithToken:#"add your access token here"];
[httpClient getPath:#"" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//
}];
Updated
Use Oauth2 Client on AFNetworking written by matt
https://github.com/AFNetworking/AFOAuth2Client
If you happen to be having this issue with Django rest framework and the routers the problem might be related to the trailing slash being clipped by the NSUrlRequest. if the trailing slash is clipped then django will have to redirect your request, to avoid this you can use Trailing_slash = True like this
router = routers.DefaultRouter(trailing_slash=False)
That way not your authorization header nor your parameters will get lost.
Hope this saves somebody some time.

Resources