Search code examples
iosobjective-ciphoneafnetworking-2afnetworking-3

status code: 400, headers in afnetworking3.0 in ios


error here This is screen shot from postman client .that api is working what is issue in my code how to set response and request . i am making a post request in objective c using the AFNetworking 3.0 but request response bad request (400) this is the errors

{ status code: 400, headers {
    "Cache-Control" = private;
    "Content-Length" = 1647;
    "Content-Type" = "text/html";
    Date = "Sat, 09 Apr 2016 15:49:32 GMT";
    Server = "Microsoft-IIS/7.5";
    "X-AspNet-Version" = "4.0.30319";
    "X-Powered-By" = "ASP.NET";
} }, NSErrorFailingURLKey=http://mytesturl_Json.svc/ValidateLoginService, com.alamofire.serialization.response.error.data=<efbbbf3c 3f786d6c

this the code to make a post request

 AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

 manager.requestSerializer = [AFJSONRequestSerializer serializer];
 manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

    [manager POST:@"http://mytesturl_Json.svc/ValidateLoginService" parameters:inputs progress:nil success:^(NSURLSessionTask *task, id responseObject) {

        NSLog(@"JSON: %@", responseObject);

    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);

    }];

i tried like this also

-(void)postdata
{
    NSError *error;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"http://virtuzo.in/AhprepaidTestService/AhprepaidAPI_Json.svc/ValidateLoginService"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];
    NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"admin", @"UserName",
                             @"1234", @"Pwd",
                             nil];
    NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
    [request setHTTPBody:postData];


    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSLog(@"reponse==%@",response);
        NSLog(@"error==%@",error);


    }];

    [postDataTask resume];

}

still i am getting same error

reponse==<NSHTTPURLResponse: 0x7f9baa433990> { URL: http://virtuzo.in/AhprepaidTestService/AhprepaidAPI_Json.svc/ValidateLoginService } { status code: 400, headers {
    "Cache-Control" = private;
    "Content-Length" = 1647;
    "Content-Type" = "text/html";
    Date = "Thu, 14 Apr 2016 02:57:21 GMT";
    Server = "Microsoft-IIS/7.5";
    "X-AspNet-Version" = "4.0.30319";
    "X-Powered-By" = "ASP.NET";
} }
2016-04-14 08:27:22.833 Ahprepaid[79163:1281702] error==(null)

Solution

  • Try different response serializer. What is the response format? is it string or is it in json format or else? according to that set response serializer. You can check your response in different tool like advance rest client, postman or you can ask to person who made api or web service..!

    Update :

    Update :
    
    NSError *error;
    
     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
      NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
      NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                      cachePolicy:NSURLRequestUseProtocolCachePolicy
                                               timeoutInterval:60.0];
    
     [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
     [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
     [request setHTTPMethod:@"POST"];
     NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST   IOS", @"name",
                 @"IOS TYPE", @"typemap",
                 nil];
     NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
     [request setHTTPBody:postData];
    
    
      NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    
      }];
    
      [postDataTask resume];
    

    Try something like this. This is native way without afnetworking. You will et data as response in your completion handler. If your response is string then convert that data to string. if response in json format then conver that data in json in completion handler block. example of conversion ,

     //data to string
      NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
     /data to json object
     NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:myNSData options:kNilOptions error:&error]; // here two posibilitiew NSArray or NSDictionary (Try both ot you can use id)
    

    Hope this will solve your problem..:)

    Update 2 :

    NSString *urlString2 = @"http://virtuzo.in/AhprepaidTestService/AhprepaidAPI_Json.svc/ValidateLoginService?UserName=admin&Pwd=1234";
    
    
    
    NSURL *myUrl = [NSURL URLWithString:urlString2];
    
    
    
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myUrl];
    [request setHTTPMethod:@"POST"];
    
    
     NSURLSession *session = [NSURLSession sharedSession];
    
    
    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"str is %@",str);
    
    
    
    
    }]resume];
    

    This is giving same response as postman. I have tried in my demo. I have just append parameters with url.

    Update 3 :

    You are getting xml String so, it's little complected to serialize.

    1) Download XML Parser. derag and drop in your project. (when you build you will get error in this class. whenever you get error comment(//) this line in this class. it's because it havent used ARC).

    updated code :

     NSString *urlString2 = @"http://virtuzo.in/AhprepaidTestService/AhprepaidAPI_Json.svc/ValidateLoginService?UserName=admin&Pwd=1234";
    
    
    
    NSURL *myUrl = [NSURL URLWithString:urlString2];
    
    
    
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myUrl];
    [request setHTTPMethod:@"POST"];
    
    
     NSURLSession *session = [NSURLSession sharedSession];
    
    
    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"str is %@",str);
    
    
    
    
        NSError *parseError = nil;
        NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
        NSLog(@" %@", xmlDictionary);
    
        NSString *myfinalString = [[xmlDictionary valueForKey:@"string"]valueForKey:@"text"];
        NSLog(@"string is %@",myfinalString);
    
    
    
        NSError *jsonError;
        NSData *objectData = [myfinalString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&jsonError];
        NSLog(@"json is : %@",json);
    
    }]resume];