3
我很努力發送POST數據到服務器並接收正確的響應。我開始使用setHTTPBody,但當我沒有得到某些POST數據的正確服務器響應時,移動到了setHTTPBodyStream,並且我讀了setHTTPBody在早期的iOS版本中發生了內存泄漏。問題是setHTTPBodyStream導致錯誤 - 「操作無法完成,連接重置由對等」。「操作無法完成,連接被同級重置。」與iOS上的NSURLConnection iOS
下面的代碼:
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"secret but correct url goes here"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
[request setHTTPMethod: @"POST"];
[request setHTTPBodyStream: [NSInputStream inputStreamWithData: [[NSString stringWithFormat:@"username=%@&password=%@&score=%i",[(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)ogl_view->username, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8) autorelease],[(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)text_field.text, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8) autorelease],ogl_view->score[0]] dataUsingEncoding:NSUnicodeStringEncoding]]];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest: request delegate:self];
if (connection){
received_data = [[NSMutableData data] retain];
ogl_view->section = CURLING_PROCESS_CREDENTIALS;
}else{
ogl_view->section = CURLING_LOGIN_OR_REGISTER;
UIAlertView *connection_alert = [[UIAlertView alloc] initWithTitle:@"Error" message: @"Can't connect to server" delegate:self cancelButtonTitle:@"Close" otherButtonTitles: nil];
[connection_alert show];
[connection_alert release];
}
我可以驗證服務器是罰款和它的作品時,我嘗試了網絡瀏覽器。
有人能讓我走上正確的軌道,正確地使用HTTP和POST方法發送數據嗎?
謝謝你的幫助。
在[github](https://github.com/caxaria/RemoteConnector)中獲得了一個示例項目,其中有幾個類用於執行請求。希望能幫助到你。 – 2011-08-16 12:16:36