Priyabrata
Priyabrata

Reputation: 1

Create and send JSON data to server using Objective C

I'm trying to send JSON data to server side using POST method, but my code gives null JSON value. I am using Objective C where I fetch data from textField and convert it into string, but after that while converting this value to JSON object, it gives null value. Don't know what to do.

Here is my code:

- (IBAction)loginAction:(UIButton *)sender
{
NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@" ,self.userNameField.text,self.passwordField.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
postData = [postData subdataWithRange:NSMakeRange(0, [postData length] - 1)];
NSData*jsonData = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingMutableContainers error:nil];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://172.31.144.227:8080/Analytics/rest/login/post"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length" ];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];

NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}

Upvotes: 0

Views: 2207

Answers (4)

Dilip Tiwari
Dilip Tiwari

Reputation: 1451

-(void)MessagePost{
NSString * post =[NSString stringWithFormat:@"http://url.com/clients/project_id=%@&user_id=58&question=%@&send_enquiry=Send",[[self.recordchat objectForKey:@"id"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[_txtfield text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@",post);
NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:post]];
[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;
postdata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnstring=[[NSString alloc]initWithData:postdata encoding:NSUTF8StringEncoding];
NSLog(@"String : %@",returnstring);
if (postdata){
    NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:postdata options:NSJSONReadingMutableContainers error:nil];
    NSDictionary* latestLoans = [dict objectForKey:@"status"];
    NSLog(@"Status dict = %@",latestLoans);
}  else{ NSLog(@"Error while posting messages.");}}

Upvotes: 1

Priyabrata
Priyabrata

Reputation: 1

Finally I wrote the correct code and it's working fine now. Please suggest me If any further modification is required.. Thank you all for your time and support.. Here is my code:

- (IBAction)loginAction:(UIButton *)sender
{
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:@"username"];
[post setValue:self.passwordField.text forKey:@"password"];


    NSArray* notifications = [NSArray arrayWithObjects:post, nil];
    NSError *writeError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
    NSString *postLength = [NSString stringWithFormat:@"%d",[jsonData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
   [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://172.31.144.227:8080/Analytics/rest/login"]]];
   [request setHTTPMethod:@"POST"];
   [request setValue:postLength forHTTPHeaderField:@"Content-Length" ];
   [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
   [request setHTTPBody:jsonData];
   NSLog(@"JSON Summary: %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
   NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
   [theConnection start];

   NSError *error = [[NSError alloc] init];
   NSHTTPURLResponse *response = nil;
   NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
   NSLog(@"Response Error= %@", response);

    if ([response statusCode] >=200 && [response statusCode] <300)
    {

    NSData *responseData = [[NSData alloc]initWithData:urlData];
    NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"Random Output= %@", jsonObject);
    [self performSegueWithIdentifier:@"DASHBOARDSEGUE" sender:sender];
    }else {
    [self alertStatus:@"Connection Failed" :@"Login Failed!"];
    }

}

Upvotes: 0

nilam_mande
nilam_mande

Reputation: 931

Try this -

- (IBAction)loginAction:(UIButton *)sender
 {
   NSDictionary *dictDetails = @{
                          @"Username" : self.userNameField.text,
                          @"Password" : self.passwordField.text
                          };

   NSString *jsonRequest = [dict JSONRepresentation];
   NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.31.144.227:8080/Analytics/rest/login/post"]];

   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

   NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

  [request setHTTPMethod:@"POST"];
  [request setHTTPBody: requestData];
  [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)   
  [requestData length]] forHTTPHeaderField:@"Content-Length"];

  [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
  [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];

  NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  [theConnection start];

  NSError *error = [[NSError alloc] init];
  NSHTTPURLResponse *response = nil;
  NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}

Upvotes: 0

Indrajit Chavda
Indrajit Chavda

Reputation: 361

instead of writing NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@" ,self.userNameField.text,self.passwordField.text];
 you should use this
    NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
    [post setValue:self.userNameField.text forKey:@"Username"];
    [post setValue:self.passwordField.text forKey:@"Password"];

Upvotes: 0

Related Questions