iosobjective-cios7

How to send raw data to API


I have one text field I need to send two data's to API.

    NSString *post =[NSString stringWithFormat:@"val1=%@,val2=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"val1"],val2];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://api.test.com/send"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSError *error;
    NSURLResponse *response;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSLog(@"log%@",str);
}
       

I need to send only raw data to API this is my code. Please check and let me know.


Solution

  • NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:someURLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSError *error = nil;
    NSHTTPURLResponse *response = nil;
    NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
    if (error)
    {
               //error
    }
    else
    {
               //no error
    }
    

    Try this