0

I have used POST method to call API with header values and params for body on my application. but on my back end couldn't able to get my header value to authenticate. even my responce has also invalid user. i have attached my snippet. could you please help me to solve this issue.

NSString *post = [NSString stringWithFormat:@"test=Message"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

[request setURL:[NSURL URLWithString:@"http://myURL.com/FakeURL"]];
[request setHTTPMethod:@"POST"];

NSString *authStr=[NSString stringWithFormat:@"userName:xxx"];
NSData *authData=[authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *headerValue=[NSString stringWithFormat:@"Basic %@",[authData base64EncodedStringWithOptions:0]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setValue:headerValue forHTTPHeaderField:@"Authorization"];


NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply);

My response has:

2017-04-10 16:43:35.635 Testing[5155:172935] ST :200
2017-04-10 16:43:35.636 API_Testing_AeroVoyce[5155:172935] Error :(null)
2017-04-10 16:43:35.638 API_Testing_AeroVoyce[5155:172935] requestReply :invalid user
ssowri1
  • 1,299
  • 2
  • 14
  • 31
  • 1
    How are you passing URL? – Abilash Balasubramanian Apr 10 '17 at 11:45
  • @AbilashBNair sorry now i updated the URL http://myURL.com/FakeURL – ssowri1 Apr 10 '17 at 11:48
  • 1
    Does it work with POSTMAN? – Larme Apr 10 '17 at 11:55
  • 1
    Take a look to how to add headers in objective C. I thing that is where you are having your issue in how you are building your request. Try a breakpoint to know the real request you are sending. http://stackoverflow.com/a/5116201/6203030 – Aitor Pagán Apr 10 '17 at 12:02
  • Could you show what you do in Postman to replicate it here? – Larme Apr 10 '17 at 12:34
  • In post man i had done what i have attached below: URL : http://myURL.com/FakeURL (POST CALL) On header : userName:xxx Body : test=Message (Encrypted Value) as x-www-form-urlencoded) – ssowri1 Apr 10 '17 at 12:50
  • 1
    Is `headerValue` the same has the one you have on POSTMAN? Since you have `application/x-www-form-urlencoded`, did you add that header? – Larme Apr 10 '17 at 14:39
  • @Larme sorry I tried application/x-www-form-urlencoded before now. but didn't worked – ssowri1 Apr 11 '17 at 07:07
  • Could you show screenshots of your POSTMAN (and potentially erase the "confidential parts")? Because, it seems that you are missing something when you try to replicate it with your code. And it's hard to guess which one, without doc or a working sample. – Larme Apr 11 '17 at 07:57
  • @Larme sorry for the delay. Eventually My friend fixed this issue. I was wrongly encrypted and header value was wrong. This is the issue what i missed to done. NSDictionary *headers = @{ username: password, @"Content-Type": @"application/x-www-form-urlencoded", @"Cache-Control" : @"no-cache", @"Postman-Token": @"01dbeecf-c6fb-f7fd-1c69-2360131e5452" }; – ssowri1 Apr 11 '17 at 14:38

1 Answers1

1

Create single URLrequest for Authorization, URL and content length:

  1. You are missing out of content-length in Request HeaderField.

     - (void)postRequest
    
     {
       NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
        NSString *post = [NSString stringWithFormat:@"test=Message"];
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
        [request setURL:[NSURL URLWithString:@"http://myURL.com/FakeURL"]];
        [request setHTTPMethod:@"POST"];
    
        NSString *authStr=[NSString stringWithFormat:@"userName:xxx"];
        NSData *authData=[authStr dataUsingEncoding:NSUTF8StringEncoding];
        NSString *headerValue=[NSString stringWithFormat:@"Basic %@",[authData base64EncodedStringWithOptions:0]];
    
        [request setValue:headerValue forHTTPHeaderField:@"Authorization"];
    
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    
    
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
            NSLog(@"requestReply: %@", requestReply);
        }];
        [task resume];
    }
    
  2. Make sure you have added NSURLSessionDataTask to resume.

  3. Also check you have enabled App Transport Security in info.Plist.

This will help to resolve your issue.

Edit:

Try to do this:

 if(data!= nil)
        {
            id JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"Response === %@",JSON);
        }

Instead of:

NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

  • Yes. I've enabled App Transport Security in info.Plist – ssowri1 Apr 10 '17 at 12:22
  • I'll try NSURLSessionDataTask – ssowri1 Apr 10 '17 at 12:22
  • @Ablilase B nair Even I called with NSURLSessionDataTask But i am getting this below issue. I have checked with back end. They told that didn't get your Credentials on your header field. Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value. – ssowri1 Apr 10 '17 at 13:12
  • Yeah I tried both NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; AND NSDictionary *Json_value = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; I'm getting empty responce when i'm using NSString and I'm getting null reswponse when i'm hit NSDictionary – ssowri1 Apr 10 '17 at 13:22
  • Just try "NSJSONReadingAllowFragments" instead of NSJSONReadingMutableLeaves – Abilash Balasubramanian Apr 10 '17 at 13:24
  • Yeah Changed to NSJSONReadingAllowFragments. but still i'm getting same @Abilash B Nair – ssowri1 Apr 10 '17 at 13:33
  • Are you sending the right value to Authorization as per Webservice requirement? – Abilash Balasubramanian Apr 10 '17 at 14:24