我正在尝试使用发布请求上传文件,但我无法附加任何其他变量。 这是代码:
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];
答案 0 :(得分:0)
在服务器端,他必须编写接受变量的代码。
答案 1 :(得分:0)
它可能对您有用。
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];
答案 2 :(得分:0)
好吧,我找到了答案,你需要在一个单独的边界之间提供每个变量,如下所示:
-----------------------------153930311422
Content-Disposition: form-data; name="var1"
value1
-----------------------------153930311422
所以这是Objective-c实现:
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]];