网络连接丢失NSURLConnection
问题描述:
每次尝试连接时都会打印此错误。不知道为什么它不能连接到服务器。建立一个简单的Java应用程序,它工作得很好。我一直在浏览*好几天试图解决这个问题。尝试了多个API和一些不恰当的东西。如果你需要更多的代码,或者有任何进一步的问题让我知道。请帮忙。 :(网络连接丢失NSURLConnection
2013年8月29日21:56:55.946恐慌[15054:70B]错误域= NSURLErrorDomain 代码= -1005 “网络连接已丢失” 的UserInfo = 0xa779a30 {NSErrorFailingURLStringKey =
http://54.221.224.251/
, 。 NSErrorFailingURLKey =http://54.221.224.251/
, NSLocalizedDescription =网络连接丢失, NSUnderlyingError = 0xa611130 “网络连接已丢失”}
这里是我的代码,设置了请求:
NSString *urlPath = [NSString stringWithFormat:@"http://54.221.224.251"];
[urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlPath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *stringdata = [NSString stringWithFormat:@"name=%@&email=%@&phash=%@",name,email,phash];
NSString *postData = [[NSString alloc] initWithString:stringdata];
[postData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection = connection;
[connection start];
这是我的代码,它应该处理PHP服务器的响应。
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receivedData appendData:data];
}
/*
if there is an error occured, this method will be called by connection
*/
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"%@" , error);
}
/*
if data is successfully received, this method will be called by connection
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"WORKED!");
}
答
而不是仅仅放置&符号,我需要像stringData那样添加它们。
NSString *stringdata = [NSString stringWithFormat:@"name=%@&email=%@&phash=%@",name,email,phash];
这解决了我的问题。
你能成功连接浏览器吗?因为你的字符串数据看起来像一个GET请求字符串,但你想做一个POST ......(我只是有点困惑) – nanako
我可以通过浏览器成功连接。它应该不是很重要,但对吗?由于网络连接丢失,错误不会被抛出,所以会出现500错误。 –
另一件奇怪的事情是,如果我将域名设置为google.com,它可以工作,所以我有点难住。 –