【发布时间】:2012-07-17 20:43:54
【问题描述】:
我尝试按照这篇帖子 iOS: how to perform a HTTP POST request? 中的说明进行操作,但不幸的是,服务器会回答但没有给我任何数据。
connection didReceiveResponse 和connectionDidFinishLoading 一样被调用,没有错误。
我做错了吗?我用Hurl.it 测试了该服务,它工作得刚刚好。
requestUrlString = 普通网址,
postString = 类似“appId=1&last_update=0”
responseData = [[NSMutableData alloc] initWithLength:0];
NSURL *baseURL = [NSURL URLWithString:[requestUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:baseURL];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d",[postString length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection start];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
NSLog(@"Connection didReceiveResponse");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
NSLog(@"Connection didReceiveData");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection Error: %@", [error description]);
[[[UIAlertView alloc] initWithTitle:@"Error"
message:[error description]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Connection didFinishLoading");
NSLog(@"data %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}
请不要参考 ASIHTTP 我这里也一样。
//编辑:我已经修复了它,很抱歉给你带来了我的问题。问题在于编码类型。
【问题讨论】:
-
我的 NSMutableData responseData 例如是空的,因为 didReceiveData 函数没有被触发。所以请求成功但我没有得到任何数据。
-
我没有给你一个完整的解决方案,但我有一些想法。查看您的代码和我的代码的差异,我看到的唯一主要问题是我没有设置 Content-Length。我想如果你设置不正确,可能会导致这个问题。这似乎是一个很长的镜头,但我会从删除它开始。另外,我建议将
statusCode记录在您的connectionDidFinishLoading中。这可能出乎意料。 -
感谢史蒂文的想法。不幸的是,删除带有 content-length 的行并不能修复它,
didReceiveResponse中的状态码是 200,所以一切都应该没问题。有没有办法获得connectionDidFinishLoading的状态?因为我那里只有一个NSURLConnection。 -
无论如何我都应该询问是否在
didReceiveResponse中检查它。所以你得到代码 200。:) -
你的代码对我来说看起来不错,除了我使用
addValue:forHTTPHeaderField。也许 URL 不是正确的,因此您没有得到响应?这是在主线程中完成的吗?
标签: ios ios5 httprequest