76947

JSON POST is not working in iOs

Question:

I am trying to post some data to the web service using JSON POST method, I have tried so many ways to do this, but none is working. Here is my code, please check:

NSArray *objects=[NSArray arrayWithObjects:@"value1", @"value2",@"value3", @"value4",@"value5", @"value6",@"value7", @"value8",@"value9", nil] ; NSArray *keys=[NSArray arrayWithObjects:@"FirstName", @"LastName",@"UserName", @"Password",@"Email", @"Gender",@"DeviceId", @"DeviceName",@"ProfileImage", nil]; NSData *_jsonData=nil; NSString *_jsonString=nil; NSURL *url=[NSURL URLWithString:urlstring]; NSDictionary *JsonDictionary=[NSDictionary dictionaryWithObjects:objects forKeys:keys]; if([NSJSONSerialization isValidJSONObject:JsonDictionary]){ _jsonData=[NSJSONSerialization dataWithJSONObject:JsonDictionary options:0 error:nil]; _jsonString=[[NSString alloc]initWithData:_jsonData encoding:NSUTF8StringEncoding]; } NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; // [request setHTTPBody:_jsonData]; // [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; // [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; // [request setValue:[NSString stringWithFormat:@"%d", [_jsonData length]] forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; NSString *finalString = [_jsonString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; [request setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]]; // //return and test NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

Please check.

Answer1:

Here is a sample code am trying to register a user. In the 'Register' button click,write the following code:

- (IBAction)registerButtonPressed:(id)sender { BOOL valid = FALSE; valid=[self validateEntry]; if(valid) { NSString *bytes = [NSString stringWithFormat:@"{\"UserName\":\"%@ %@\",\"Email\":\"%@\",\"UserType\":\"normaluser\",\"Password\":\"%@\"}",firstName,lastName,email,password]; NSURL *url=[NSURL URLWithString:urlstring]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:[bytes dataUsingEncoding:NSUTF8StringEncoding]]; [self setUrlConnection:[NSURLConnection connectionWithRequest:request delegate:self]]; [self setResponseData:[NSMutableData data]]; [self.urlConnection start]; } }

Then add the following as Connection delegate methods:

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [self.responseData setLength:0]; } - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.responseData appendData:data]; } - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Status" message:@"Sorry,Network is not available. Please try again later." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alert show]; } - (void) connectionDidFinishLoading:(NSURLConnection *)connection { if (connection == self.urlConnection) { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; NSError *error; NSDictionary *jsonString=[NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error]; if(jsonString != nil) { if ([[[jsonString objectForKey:@"data"] objectForKey:@"id"] length]) { [[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:@"data"] objectForKey:@"id"] forKey:@"user_id"]; [[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:@"data"] objectForKey:@"UserName"] forKey:@"user_name"]; [[NSUserDefaults standardUserDefaults] synchronize]; [delegate userRegistrationViewControllerResponse:self]; } else { UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"Info" message:[jsonString objectForKey:@"statusText"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [alertView show]; } } else { UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"Server Busy" message:@"Register after sometime" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [alertView show]; } } } <ul><li>This will post the user information as JSON.</li> </ul>

Answer2:

Try this one....

NSURL *aUrl = [NSURL URLWithString:@"https://www.website.com/_api/Login/"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:0.0]; [request setHTTPMethod:@"POST"]; NSString *postString = [NSString stringWithFormat:@"EmailAddress=%@&UserPassword=%@",uName.text,pwd.text]; [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; [[NSURLConnection alloc] initWithRequest:request delegate:self];

-Than call the NSURLConnection delegate methods.. dot forgot to alloc the responseData....

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [responseData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; responseData = nil; json =[[responseString JSONValue] retain]; NSLog(@"Dict here: %@", json); }

Answer3:

The request should be something along these lines...

NSURL * url = [NSURL URLWithString:@"your_url"]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; NSError * error = nil; NSData * postData = [NSJSONSerialization dataWithJSONObject:your_json_dictionary_here options:NSJSONReadingMutableContainers error:&error]; [request setHTTPBody:postData];

I also suggest to check your response to find out why is your request failing. Is it on the client side or server side (and why?)...

Recommend

  • Use of colon in variable declaration [duplicate]
  • how much time does grid.py take to run?
  • How to POST JSON data using NSURLSession in swift
  • SQL Regex get phone number
  • iOS: how to get the http connection's source port
  • Alamofire timeout not working in Swift 3
  • Sending multipart request from iPhone to Ruby on Rails (RoR) server
  • Express: Req.body is undefined after POST req
  • AngularJS $http return value
  • The required anti-forgery cookie “__RequestVerificationToken” is not present. MVC 5
  • Express.js : POST data as KEY of a req.body object instead of VALUE of req.body?
  • Exception creating JSON with LINQ
  • Yii2: Finding file and getting path in a directory tree
  • Clear activity stack before launching another activity
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • How do I configure context broker accept post requests from my remote sensor?
  • Apache RewriteRule redirection with url encoded
  • chrome.tabs.executeScript only fires when the Developer Console is open
  • Play WS (2.2.1): post/put large request
  • Different response to non-authenticated users and AJAX calls
  • Optimizing database types to compact database (SQLite)
  • C# - Serializing and deserializing static member
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • Cross-Platform Protobuf Serialization
  • Sending data from AppleScript to FileMaker records
  • jQuery tmpl and DataLink beta
  • Do I've to free mysql result after storing it?
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • How to include full .NET prerequisite for Wix Burn installer
  • SQL merge duplicate rows and join values that are different
  • Proper way to use connect-multiparty with express.js?
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • Free memory of cv::Mat loaded using FileStorage API
  • How to set the response of a form post action to a iframe source?
  • How do I configure my settings file to work with unit tests?
  • Turn off referential integrity in Derby? is it possible?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Is it possible to post an object from jquery to bottle.py?
  • Binding checkboxes to object values in AngularJs