0

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];
}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    Data you are sending is not in json format. You seem to be new to this. Please refer json.org – Deepak Thakur Sep 24 '15 at 09:44
  • 1
    Congratulations. You achieved a code injection in your very first line of code, a severe vulnerability. Second, you are posting a username and password to an http address. Everybody can listen to that message and extract the username and password. – gnasher729 Sep 24 '15 at 09:45
  • Refer this link dear.. http://stackoverflow.com/questions/19807368/sending-data-to-post-json-web-service-through-ios – Deepak Thakur Sep 24 '15 at 09:47
  • I would recommend you to create NSError object and put in method that creates json object. If you get nil from that operation, than examine error and you will see why. – kirander Sep 24 '15 at 09:48
  • Reading through your code, this is so full of bugs.... I make a suggestion. You fix the first bug (the fact that "post" will contain dangerous nonsense depending what is contained in userNameField.text and passwordField.text), and then I'll tell you the next bug. – gnasher729 Sep 24 '15 at 09:49
  • Thank you guys...Thanks for your valuable time and suggestions..Yes, I'm new to objective C..So definitely I'll follow your suggestions and look into my codes for errors...Thank you again.. :-) – Priyabrata Sep 24 '15 at 10:52

4 Answers4

1
-(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.");}}
Dilip Tiwari
  • 1,441
  • 18
  • 31
0
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"];
Indrajit Chavda
  • 361
  • 1
  • 2
  • 13
  • Hi Indrajit...Thanks for the suggestion...I'll definitely let you know if further any problem I'm gonna face in my program....Thanks again... :-) – Priyabrata Sep 24 '15 at 10:59
0

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];
}
nilam_mande
  • 931
  • 7
  • 14
  • Hi nilam,after using your code..it's showing "No visible @interface for "NSMutableDictionary" declares the selector "JSONRepresentation".. could you please help me out.... looking forward to your reply.. Thank You.. :-) – Priyabrata Sep 24 '15 at 10:56
0

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!"];
    }

}