Sending an HTTP POST with header form-data request on iOS - ios

I am calling odata post api having HTTP header filed is "form-data". Below is my code :-
NSURL *restURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:restURL];
[request setHTTPMethod: getorpost];
if (jsonData != nil) {
[request setValue:#"application/form-data" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
}
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
responseData = [[NSMutableData alloc] init];
}
And i am getting below response:-
Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details
But, it is working fine in Postman. Can anyone please suggest where is the fault in my code.
Thanks,

Use this
NSURL *url = [NSURL URLWithString:url_str];
NSLog(#"%#",datastring);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSMutableData *requestBody = [[NSMutableData alloc] initWithData:[datastring dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"no-cache" forHTTPHeaderField:#"Cache-Control"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestBody length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestBody];
httpResponse=[[NSHTTPURLResponse alloc]init];
receivedData=[[NSMutableData alloc]init];
connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(connection)
{
NSLog(#"%# calling with datastring: %#", url, datastring);
}
delegates
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%d", httpResponse.statusCode);
NSLog(#"%#",[httpResponse description]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
receivedData = [[NSMutableData alloc]init];
httpResponse=[[NSHTTPURLResponse alloc]init];
NSLog(#"%#",[NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSString *retVal = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"retVal=%#",retVal);
}

-(void)ViewDidLoad
{
NSMutableDictionary *postData = [[NSMutableDictionary alloc]init];
[postData setObject:uid forKey:#"id"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postData options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"%#",jsonInputString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"YOUR URL "]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[request setURL:url];
[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 *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *jsonDict;
if (responseData != nil)
{
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"jsonDoct == %#",jsonDict);
}
else
{
NSLog(#"RESONPSE IS NULL");
}
if (error)
{
NSLog(#"error %#",error.description);
}
}

Related

Calling web services with the help of AFNetworking in Objective C

I am using NSURLConnection method to call the web services what I want is to replace it with 3rd party library AFNetworking how shall I achieve this I am calling the web Services with data first time here is what I am doing currently.
- (void)viewDidLoad {
[super viewDidLoad];
NSURL * linkUrl = [NSURL URLWithString:#URLBase];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:linkUrl];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[str length]];
[theRequest addValue: #"text/plain; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [str dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData alloc] init];
}
else
{
NSLog(#"theConnection is NULL");
}
}
#pragma mark -- Connection Delegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//NSLog(#"%#",response);
//[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"\nERROR with theConenction");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseDataString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"Converted NSData %# ",responseDataString);
}
here
[theRequest setHTTPBody: [str dataUsingEncoding:NSUTF8StringEncoding]];
str is my encrypted data like username and password.
thanks in advance.!
You need to send POST request to your web services. You can use below code snippet for old way.
NSString *post = [NSString stringWithFormat:#"%#&value=%#&value=%#&value=%#&value=%#&value=%#",self.Comment_Memberid,self.SharedID,self.Post_Ownerid,self.commentText.text,email_stored,password_stored];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://.../api/json/postcomment/"]]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/plain; charset=utf-8" forHTTPHeaderField:#"Content-type"];
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:postData];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %ld", (long)[urlResponse statusCode]);
if ([urlResponse statusCode] == 200)
{
}
And if you want to send POST request using with AFNetworking you can use below code:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"34": x,
#"130": y};
[manager POST:#"https://../api/json/cordinates" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

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

How to send an object as a parameter for a POST request in iOS?

I need to bind parameters in an object and pass the object as a POST request to receive a successful piece of information from an API.
{
customer = {
"auth_token" = "";
"device_id" = 3e708bf1a49cdd06;
"email_address" = "abc#xyz.in";
name = abc;
number = 1234567890;
"resend_token" = true;
};
}
This is the object that I need to send along with the post request. But when I convert it into a string and post it, the entire object becomes the key and the value becomes nil. It gets posted as {"{customer.....}=>nil}.
The object should be posted as
{"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc#xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}
This my current attempt:
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setHTTPMethod:#"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
A lot of the code used here was used without a proper understanding and directly taken from other StackOverflow answers, so please excuse any bad programming practice.
How can I do this? Any help is appreciated. Thank you.
you can try below code.Instead of converting data to string set it as HTTPBody like
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = temp;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Following is the sample code for sending a POST request to server.
-(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
requestDic = [NSDictionary dictionaryWithDictionary:data];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Request Object:\n%#\n",data);
NSLog(#"Request String:\n%#\n",jsonString);
NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[theReq addValue: #"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theReq setHTTPMethod:#"POST"];
[theReq addValue:[NSString stringWithFormat:#"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:#"Content-Length"];
[theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
}
May this help lot and resolve your problem.
NSString *post =[[NSString alloc] initWithFormat:#"id=%d&restaurant_name=%#", restaurnt_Id, _rest_NameTxt.text];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"APPLICATION/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"APPLICATION/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
_responseData = [[NSMutableData alloc] init];
[NSURLConnection connectionWithRequest:request delegate:self];
pragma mark - connection methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_responseData setLength:0];
[_responseCityData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
[_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[COMMON showErrorAlert:#"Internet Connection Error!"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
NSLog(#"%#", responseString);
}
Make your task in connectionDidFinishLoading method

nsurlsessiondatatask returns nil while sending a post request to REST based url ios

-(void)showData {
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"1", #"number",nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
NSLog(#"data is %#", data );
NSLog(#"response is %#" , response);
}];
[postDataTask resume];
}
when i execute the code the debugger jumps from the NSURLSessionDataTask and log generated is __NSCFLocalDataTask: 0x7ff061751960>{ taskIdentifier: 1 } { suspended } and does not come any data in NSData and NSResponse.
#interface UrClass:NsObject<NSURLConnectionDelegate>{ NSMutableData *_receivedData;
}
-(void)showData{
NSString * urlStr = [NSString stringWithFormat:#"%#", path];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setURL:[NSURL URLWithString:urlStr]];
NSString *requestStr = [dictionary JSONRepresentation];
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", (unsigned int)[requestData length]];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:requestData];
[theRequest addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setTimeoutInterval:REQUEST_TIME_OUT_SECS];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:NO];
[theConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[theConnection start];
if (theConnection)
_receivedData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
Try this code:
NSURL *url=[NSURL URLWithString:#"https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts"];
NSData *contactData=[NSData dataWithContentsOfURL:url];
NSMutableArray *allContectData=[NSJSONSerialization JSONObjectWithData:contactData options:0 error:nil];
NSLog(#"%#",allContectData);
Otherwise use this code
-(void)showData{
NSString *urlString = #"https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NO timeoutInterval:20.0f];
responseData = [[NSMutableData alloc] init];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
use NSURLConnectionDataDelegate Delegate Method
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSMutableArray *allContectData=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",allContectData);
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#",error);
}

NSURLConnection JSON Submit to Server

I am at a loss here, I thought I'd try something new with web services for my app.
I can pull data down no problem, but I am trying to post to the server and just can seem to get this to even fire.
What I am intending to happen is on submit button press the action be fired:
- (IBAction)didPressSubmit:(id)sender {
//JSON SERIALIZATION OF DATA
NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
[projectDictionary setObject:[projectName text] forKey:#"name"];
[projectDictionary setObject:[projectDescShort text] forKey:#"desc_short"];
[projectDictionary setObject:[projectDescLong text] forKey:#"desc_long"];
NSError *jsonSerializationError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
if(!jsonSerializationError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Serialized JSON: %#", serJSON);
} else {
NSLog(#"JSON Encoding Failed: %#", [jsonSerializationError localizedDescription]);
}
// JSON POST TO SERVER
NSURL *projectsUrl = [NSURL URLWithString:#"http://70.75.66.136:3000/projects.json"];
NSMutableURLRequest *dataSubmit = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[dataSubmit setHTTPMethod:#"POST"]; // 1
[dataSubmit setValue:#"application/json" forHTTPHeaderField:#"Accept"]; // 2
[dataSubmit setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"]; // 3
[dataSubmit setHTTPBody: jsonData];
[[NSURLConnection alloc] initWithRequest:dataSubmit delegate:self];
}
After that it runs through:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"DidReceiveResponse");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
NSLog(#"DidReceiveData");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"BLAH CHECK YOUR NETWORK" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
I am obviously missing something, but I don't even know where to look. All I need is a point in the right direction, any help would be great.
UPDATE
I was able to get the request to fire with the following.
Okay I was able to get the request to fire using the following:
- (IBAction)didPressSubmit:(id)sender {
NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
[projectDictionary setObject:[projectName text] forKey:#"name"];
[projectDictionary setObject:[projectDescShort text] forKey:#"desc_small"];
[projectDictionary setObject:[projectDescLong text] forKey:#"desc_long"];
NSError *jsonSerializationError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
if(!jsonSerializationError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Serialized JSON: %#", serJSON);
} else {
NSLog(#"JSON Encoding Failed: %#", [jsonSerializationError localizedDescription]);
}
NSURL *projectsUrl = [NSURL URLWithString:#"http://70.75.66.136:3000/projects.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:#"POST"]; // 1
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"]; // 2
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"]; // 3
[request setHTTPBody: jsonData]; // 4
(void) [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
But for some reason the post method only received a bunch of nil values, I am getting this from the server side. Processing by ProjectsController#create as JSON
Parameters: {"{\n \"desc_long\" : \"a\",\n \"name\" : \"a\",\n \"desc_small\" : \"a\"\n}"=>nil}
UPDATE 2
With a little read from here: http://elusiveapps.com/blog/2011/04/ios-json-post-to-ruby-on-rails/
I was able to see if missed the following line.
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
So final didPressSubmit code is as follows;
- (IBAction)didPressSubmit:(id)sender {
NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
[projectDictionary setObject:[projectName text] forKey:#"name"];
[projectDictionary setObject:[projectDescShort text] forKey:#"desc_small"];
[projectDictionary setObject:[projectDescLong text] forKey:#"desc_long"];
NSError *jsonSerializationError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
if(!jsonSerializationError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Serialized JSON: %#", serJSON);
} else {
NSLog(#"JSON Encoding Failed: %#", [jsonSerializationError localizedDescription]);
}
NSURL *projectsUrl = [NSURL URLWithString:#"http://70.75.66.136:3000/projects.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:#"POST"]; // 1
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"]; // 2
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"]; // 3
[request setHTTPBody: jsonData]; // 4
(void) [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
I got same issue but I resolved it by setting the options to nil.
Replace
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
by
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:nil error:&jsonSerializationError];
Use option to nil if you are sending json to server, if you are displaying json use NSJSONWritingPrettyPrinted.
Hope this will help you.

Resources