I'm trying to upload a file using post request but I can't append any other variables with it . Here is the code :
NSMutableURLRequest *urlRequest =
[NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:
[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry]
forHTTPHeaderField:@"Content-Type"];
NSString *post = @"key1=val1&key2=val2";
NSData *postVars = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableData *postData =
[NSMutableData dataWithCapacity:[data length]+[postVars length] + 512];
[postData appendData:postVars];
[postData appendData:
[[NSString stringWithFormat:@"--%@\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:
[[NSString stringWithFormat:
@"Content-Disposition: form-data; name=\"%@\"; filename=\"test.bin\"\r\n\r\n", FORM_FLE_INPUT]
dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:data];
[postData appendData:
[[NSString stringWithFormat:@"\r\开发者_运维百科n--%@--\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:postData];
In the serverside he has to write the code which will accept the variables.
It may be useful to you.
NSString *post = @"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
Well , i found the answer , you need to provide every variable between a separate boundary like the following :
-----------------------------153930311422
Content-Disposition: form-data; name="var1"
value1
-----------------------------153930311422
So here is objective-c implementation :
SString *boundary = [NSString stringWithString:@"-----------------------------153930311422 "];
NSMutableURLRequest *urlRequest =[NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry] forHTTPHeaderField:@"Content-Type"];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=var1 \r\n\r\n %@ \r\n\r\n",value1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
精彩评论