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];
}
6
  • 1
    Data you are sending is not in json format. You seem to be new to this. Please refer json.org Commented Sep 24, 2015 at 9: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. Commented Sep 24, 2015 at 9:45
  • Refer this link dear.. stackoverflow.com/questions/19807368/… Commented Sep 24, 2015 at 9: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. Commented Sep 24, 2015 at 9: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. Commented Sep 24, 2015 at 9:49

4 Answers 4

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.");}}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Dilip Tiwari .Really appreciate you help.
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"];

1 Comment

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... :-)
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];
}

1 Comment

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.