Nick
Nick

Reputation: 71

Send JSON data with NSURLConnection in Xcode

I am trying to send JSON data to a web server via the code below. For some reason, the request does not seem to be going out. What does it look like I am missing? Also the result from NSURLConnection (retStr) is always empty?

NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"value1"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];

    NSURL *url = [NSURL URLWithString:@"http://webserveraddress"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:nil timeoutInterval:60];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:jsonData];
NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];

Upvotes: 4

Views: 12011

Answers (3)

Nicolas Manzini
Nicolas Manzini

Reputation: 8546

To send simple data in post vars to your webserver running php you simply do this in

Example

NSString * key = [NSString stringWithFormat:@"var1=%@&var2=%@&var3=%@",@"var1String" ,@"var2string" ,[NSnumber numberWithBool:YES]];

NSURL * url = [NSURL URLWithString:@"http://webserver.com/yourScriptPHP.php"];

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:[key dataUsingEncoding:NSUTF8StringEncoding]];

[[NSURLConnection alloc] initWithRequest:request delegate:self];
// this is for you to be able to get your server answer. 
// you will need to make your class a delegate of NSURLConnectionDelegate and NSURLConnectionDataDelegate
myClassPointerData = [[NSMutableData data] retain];

Implement

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [myClassPointerData appendData:data]
}

-(void)connection:(NSURLConnection *)connection DidFinishLoading {
    // do what you want with myClassPointerData the data that your server did send you back here
    // for info on your server php script you just need to do: echo json_encode(array('var1'=> $var1, 'var2'=>$var2...));
    // to get your server sending an answer
}

Upvotes: 3

codeburn
codeburn

Reputation: 2004

Instead of sending as JSON, you could simply send it the normal way - by setting the request's HTTPBody with POST method.

Only differenc you need to make if you need to make a call such as 'http://abc.example.com/user_profile.json?user[first_name]=fdffdf&user[last_name]=dffdf'

is, you need to have your dictionary keys have a prefix. That is, 'first_name=fdffdf' needs to be changed to 'user[first_name]=fdffdf'.

Try this bit of code to change your parameter dictionary to the required format for JSON..

for (id key in [self allKeys]) {
NSString *newKey = [NSString stringWithFormat:@"%@[%@]", parent, key];
[result setObject:[self objectForKey:key] forKey:newKey];
} 

Upvotes: 0

ganesh manoj
ganesh manoj

Reputation: 977

once check like this

ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"ur url"]];

[request setPostValue:appdelegate.userid forKey:@"userid"];
[request setPostValue:self.nameLbl.text forKey:@"username"];
[request setPostValue:self.website.text forKey:@"website"];

NSLog(@"~~~~~~ request~~~~~ %@",request);

[request setTimeOutSeconds:5000];
[request startSynchronous];

Upvotes: 0

Related Questions