NSMutableURLRequest setHTTPBody
i took this code from a different question and my script file has more inputs, not just mydata, also the data going into the mydata should not be static text, it should be from a NSString.
So my question is, how do i post multiple pieces of data to my script and how would I input a value from a NSString because my understand is i cannot use NSStrings with c data types. not sure if thats the correct terminology so please correct me if i am wrong.
const char *bytes = "mydata=Hello%20World";
NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/script.php"];
NSMutableURLRequest *request = [NSMutableURLRequest r开发者_Go百科equestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseString = [[NSString alloc] initWithFormat:@"%@", responseData];
NSLog(@"responseData: %@", responseData);
userData = responseData;
New issue using answer below
NSMutableData *data = [NSMutableData data];
NSString *number = numberIB.text;
NSString *name = nameIB.text;
NSString *nameString = [[NSString alloc] initWithFormat:@"name=", name];
NSString *numberString = [[NSString alloc] initWithFormat:@"number=", number];
NSLog(nameString);
NSLog(numberString);
[data appendData:[nameString dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[numberString dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:@"http://www.siteaddress.com/test.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
//[request setHTTPBody:[NSData dataWithBytes:data length:strlen(data)]];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseString = [[NSString alloc] initWithFormat:@"%@", responseData];
NSLog(@"responseData: %@", responseData);
the NSLogs for nameString and numberString come back name= and number= without any data. causing no data to be sent to my script.
You can use an NSMutableData
object to append bytes as needed, like so:
NSMutableData *data = [NSMutableData data];
const char *bytes = "mydata=Hello%20World";
[data appendBytes:bytes length:strlen(bytes)];
//...
const char *moreBytes = "&someMoreData=Fantastic";
[data appendBytes:moreBytes length:strlen(moreBytes)];
Edit: If you want to append a NSString
into the data buffer, you can use -[NSString dataUsingEncoding:]
and pass it off to -appendData:
NSString *someString = @"blah";
[data appendData:[someString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:data];
精彩评论