我正在努力将POST数据发送到服务器并收到正确的响应。我开始使用setHTTPBody,但当我没有获得某些POST数据的正确服务器响应时移动到setHTTPBodyStream,我读到setHTTPBody在早期的iOS版本上有内存泄漏。问题是setHTTPBodyStream导致错误 - “操作无法完成。连接由同行重置”。
以下是代码:
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方法发送数据吗?
感谢您的帮助。
答案 0 :(得分:0)
尝试使用此(使用您自己的值):
NSString* post = @"username=myUser&password=myPass&score=20"; //customize this
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:@"http://my.request.com"]; //customize this
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:timeout];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
然后,您需要实现NSURLConnectionDelegate方法:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)remoteData;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
最后,请记得发布NSURLConnection。
编辑:没看到你写的那个setHTTPBody泄漏......从未见过这种情况。无论如何,这里有一些应该有用的代码......