0

Im trying to send JSON object to php server from my iphone

The server will decode it do some functions and then replay with JSON back to iphone.

I have the the server set up but im not sure what methods I need to use to connect to the php server (using POST method) and also how the iphone will get the response from the server.

SeRo
  • 77
  • 4
  • 15

2 Answers2

2

here is your code enjoy

NSString *urlString = @"Your url";

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSMutableData *body = [NSMutableData data];


NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];




[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];



// Text parameter1
// NSString *param1 = @"parameter text";
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];



// Another text parameter
// NSString *param2 = @"Parameter 2 text";
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"desc\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param2] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];


// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];

like above code u can send the multiple value using HTTP post method.

freelancer
  • 1,658
  • 1
  • 16
  • 37
  • Thanks for the help, but how about getting a response from server how will the iphone catch it ? – SeRo Apr 14 '12 at 17:31
0

Check this out for POSTing data: iPhone sending POST with NSURLConnection

How can you have a JSON object in Cocoa? You somehow have to convert whatever data you have to JSON, send it to the server and then parse the answer.

Community
  • 1
  • 1
Christian Schnorr
  • 10,768
  • 8
  • 48
  • 83