通过HTTP Post发送表单数据[Objective C]

时间:2011-03-30 13:21:49

标签: iphone objective-c variables post http-post

我有一个来自iphone应用程序的表单数据,需要将HTTP Post变量发送到URL。

问题是,我被告知不要使用setHTTPBody,但我不确定如何做到这一点,因为我看到的每个例子都使用setHTTPBody;甚至那些使用POST方法的人。

为了使事情变得更复杂,网址/网页在帖子变量中需要submit=trueaction=enquiry

这是我到目前为止所拥有的。

NSString *formContactName   = [self contactName];
NSString *formEmail     = [self email];
NSString *formPhone     = [self phone];
NSString *formComments      = [self comments];

// The above data is fine, as explored here.
NSLog(@"formContactName = %@", formContactName);
NSLog(@"formEmail = %@", formEmail);
NSLog(@"formPhone = %@", formPhone);
NSLog(@"formComments = %@", formComments);

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

// set headers
NSString *contentType = [NSString stringWithFormat:@"text/plain"];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

// setup post string
NSMutableString *postString = [[NSMutableString alloc] init];   
[postString appendFormat:@"contactname=%@", formContactName];
[postString appendFormat:@"&email=%@", formEmail];
[postString appendFormat:@"&phone=%@", formPhone];
[postString appendFormat:@"&comments=%@", formComments];
[postString appendFormat:@"&submit=yes"];
[postString appendFormat:@"&action=enquiry"];

// I've been told not to use setHTTPBody for post variables, but how else do you do it?
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

// get response
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];

NSData *responseData = [NSURLConnection sendSynchronousRequest:request 
                         returningResponse:&urlResponse 
                                     error:&error];

NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];


NSLog(@"Response code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >=200 && [urlResponse statusCode] <300)
{
NSLog(@"Response ==> %@", result);
}

[result release];
[error release];

我总是得到200分,这很好。但回复表明Post变量没有通过。

回复中有一个名为“enquirysent”的字段,它始终为空白。如果Post变量成功,则应返回“1”或true语句。

"enquirysent": ""

因此,我的问题是:如何在上述请求中强制使用HTTP-POST变量?

感谢。

1 个答案:

答案 0 :(得分:4)

您可以使用ASIHTTPRequest来简化:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];