【发布时间】:2012-01-30 14:41:26
【问题描述】:
我花了很多时间研究使用 Cocoa 的 POST 请求。
我发现了一些看起来不错的代码。我改变了它,就像它适合我的需要一样。但是代码不起作用,我找不到错误,因为我对可可很陌生。
这是我的代码。
- (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 消息是“网络请求已启动”和“连接已启动”。
所以我认为- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 和- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 没有被调用。
谁能帮我解决这个问题?
谢谢你的帮助,朱利安
【问题讨论】:
标签: html cocoa xmlhttprequest http-post httpresponse