我花了很多時間研究使用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