2011-12-25 49 views
0

我想发送一个异步http请求到服务器(在我的情况下是django)。 出于某种原因,它调用didFailWithError方法 - 这意味着它不起作用。 这是我的代码:iPhone - NSURL连接

responseData = [NSMutableData data]; 
baseURL = [NSURL URLWithString:@"http://localhost:8000/messages/views/new_messages/"]; 
NSURLRequest *request = 
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/messages/views/new_messages/"]]; 
[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

return TRUE; 
} 

,这些都是连接的方法:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse   *)response 
{ 
    [responseData setLength:0]; 
    NSLog(@"part 1 works"); 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [responseData appendData:data]; 
    NSLog(@"part 2 works"); 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"error!!!"); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSLog(@"finish"); 
} 
  1. 有什么错呢?
  2. 我纠正它后 - 我怎样才能发送帖子参数通过这个服务器?

感谢

回答

1

试着用替换你的错误电话:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"Error: %@\n%@", [error localizedDescription], [error userInfo]); 
} 

这会给你什么地方出了错更好的日志记录,因为它使用在传递的实际NSError参数

你也可以根据。在返回对象的格式上,尝试转换你的responseData并显示它。我曾与REST服务合作,将它们的错误消息作为responseData中的JSON字典返回,所以我可以将其转换并查看服务器在发生错误时如何响应,但这取决于您要连接的服务器。

2

如果你也想发布一些参数传递给服务器,那么你需要需要以下各项

NSString *arguments = [[NSString alloc] initWithFormat:@"my arguments"]; 
[myRequest setHTTPMethod:@"POST"]; 
[myRequest setHTTPBody:[arguments dataUsingEncoding:NSUTF8StringEncoding]]; 

这样就可以根据需要发送尽可能多的参数。

+0

谢谢!这就是我一直在寻找的 – 2011-12-25 13:32:25