0

I am trying to call a web service with these parameters:

{"Class":"Authorization","method":"login","user":"","pass":""}

as follows

NSString *user = [NSString stringWithFormat:@"username=%@",_username.text];
NSString *pass = [NSString stringWithFormat:@"password=%@",_password.text];
NSString *Class = @"Authorization";
NSString *method = @"login";

//NSString *post = [NSString stringWithFormat:@"%@&%@&%@&%@", user, pass, Class, method ];
    
NSString *jsonPostBody = [NSString stringWithFormat:@"'json' = '{\"Class\":"
                              "\"%@\""
                              ",\"method\":"
                              "\"%@\""
                              ",\"pass\":"
                              "\"%@\""
                              ",\"user\":"
                              "\"%@\""
                              "}'",
                              [Class stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [method stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [pass stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [user stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
   
    NSURL *url = [NSURL URLWithString:@"http://212.119.87.45:8080/IktissabServices/index.php/service"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:180.0];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded"   forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[[jsonPostBody stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
                          dataUsingEncoding:NSUTF8StringEncoding
                          allowLossyConversion:YES]];
    
    [request setHTTPBody:postData];
    
    NSString* postDataLengthString = [[NSString alloc] initWithFormat:@"%d", [postData length]];
    [request setValue:postDataLengthString forHTTPHeaderField:@"Content-Length"];
    
    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSError *error;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];//
    if (! error) {
        NSLog(@"%@",jsonDict);
    }else{
        NSLog(@"%@",error.localizedDescription);
    } 

Every time the result is:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

The web service has:

input-content-type: text/json

output-content-type: text/json

Any help or examples will be appreciated.

Community
  • 1
  • 1
  • when testing and calling the webservices via login the statement will appear Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil' – Mohammed Abdelrasoul Nov 14 '12 at 13:59
  • it return to you result ? how and it is terminated from my side kindly send me result – Mohammed Abdelrasoul Nov 14 '12 at 14:08
  • @MohammedAbdelrasoul I've updated my answer, but can't test it without access to server, so perhaps you can let me know how it goes. And if you continue to get exception, let us know which line of code is generating the `NSInvalidArgumentException`. – Rob Nov 14 '12 at 15:18
  • Please refer to this answer: http://stackoverflow.com/a/4466899/268627 – o15a3d4l11s2 Nov 14 '12 at 15:21

1 Answers1

0

I'm not getting any exception with the following code (though obviously I don't have access to your server, so I can't test it end-to-end):

NSDictionary *dictionary = @{
    @"Class"  : @"Authorization",
    @"method" : @"login",
    @"pass"   : _password.text,
    @"user"   : _username.text
};

NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                   options:0
                                                     error:&error];
if (error)
    NSLog(@"Failure to serialize JSON object %@", error);

NSURL *url = [NSURL URLWithString:@"http://212.119.87.45:8080/IktissabServices/index.php/service"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                   timeoutInterval:180.0];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];    
[request setHTTPBody:postData];

NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
    NSLog(@"%s sendSynchronousRequest error %@", __FUNCTION__, error);

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];//
if (!error) {
    NSLog(@"%@",jsonDict);
} else {
    NSLog(@"%s JSONObjectWithData error %@", __FUNCTION__, error);
} 

Or, if you're not using the latest Xcode and don't have access to the Modern Objective C definition of the dictionary, you could obviously define your dictionary the traditional way:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"Authorization", @"Class",
                            @"login",         @"method",
                            _password.text,   @"pass",
                            _username.text,   @"user",
                            nil];

Edit:

Inferring from your jsonPostBody, the dictionary entry might need to be:

NSDictionary *dictionary = @{
    @"json" : @{
        @"Class"  : @"Authorization",
        @"method" : @"login",
        @"pass"   : _password.text,
        @"user"   : _username.text
    }
};

or possibly (though, even less likely), inferring from your user and pass definitions:

NSDictionary *dictionary = @{
    @"json" : @{
        @"Class"  : @"Authorization",
        @"method" : @"login",
        @"pass"   : [NSString stringWithFormat:@"password=%@",_password.text],
        @"user"   : [NSString stringWithFormat:@"username=%@",_username.text]
    }
};

It's a question of how the JSON needs to be formatted for your server.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • i tried the all suggestion an give me error when calling the webservices 2012-11-14 20:13:46.852 Iktissab Demo1[483:11303] -[login getlogin:] JSONObjectWithData error Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7496d40 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} – Mohammed Abdelrasoul Nov 14 '12 at 17:15
  • @MohammedAbdelrasoul I can't answer that as I don't know precisely how the JSON request has to be formed for your web service. Hopefully your server team can shed some light on this. I've thrown three different permutations of the request, based solely upon what I inferred from your code sample, but I'm not at all sure what your webservice requires. When I was testing, I also did a `NSLog(@"responseData = %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);` so I could see the full text of my server's response, so perhaps similar debugging might help you. – Rob Nov 14 '12 at 20:40
  • Thanks Rob, but the [roblem appear from NSString *jsonresult = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error]; – Mohammed Abdelrasoul Nov 15 '12 at 09:17
  • the error : The operation couldn’t be completed. (Cocoa error 3840.)" – Mohammed Abdelrasoul Nov 15 '12 at 09:25
  • You need to examine the actual server `responseData` to see what the server said. Most likely the request was not formatted correctly. – Rob Nov 15 '12 at 15:29
  • Thanks Rob for your help you are my Hero :), fixed now the error was with the input parameter from server side thanks again – Mohammed Abdelrasoul Nov 16 '12 at 14:27
  • @MohammedAbdelrasoul Excellent. By the way, I'd be grateful if you would click the "up arrow" next to my original answer if it was helpful and/or click the checkmark if I solved your problem. Thanks! – Rob Nov 16 '12 at 14:49