我花了很多时间研究使用Cocoa的POST请求。Cocoa HTTP POST请求[Mac OS X]
我发现一些看起来不错的代码。我改变了它,因为它符合我的需求。但是代码没有工作,我找不到这个bug,因为我对可可非常陌生。
这是我的代码。
- (IBAction)sendForm:(id)sender
{
NSLog(@"web request started");
NSString *post = [NSString stringWithFormat:@"firstName=%@&lastName=%@&eMail=%@&message=%@", firstName.stringValue, lastName.stringValue, eMail.stringValue, message.stringValue];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"myDomain/form.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
webData = [[NSMutableData data] retain];
NSLog(@"connection initiated");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
NSLog(@"connection received data");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"connection received response");
NSHTTPURLResponse *ne = (NSHTTPURLResponse *)response;
if([ne statusCode] == 200)
{
NSLog(@"connection state is 200 - all okay");
NSString *html = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
[[webView mainFrame] loadHTMLString:html baseURL:[NSURL URLWithString:@"myDomain"]];
}
}
但是我收到的唯一两条NSLog消息是“web请求启动”和“连接启动”。 所以我认为- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
和- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
没有被调用。
任何人可以帮助我这个问题?
感谢您的帮助,朱利安
什么是webdata? – RollRoll 2013-06-15 18:58:48