【发布时间】:2013-09-02 15:30:24
【问题描述】:
每次我尝试连接时都会打印此错误。不知道为什么它无法连接到服务器。构建了一个简单的java应用程序,它运行良好。几天来,我一直在浏览 StackOverflow 试图解决这个问题。尝试了多个 API 和一些不正确的东西。如果您需要更多代码,或者有任何其他问题,请告诉我。请帮忙。 :(
2013-08-29 21:56:55.946 恐慌[15054:70b] 错误域 = NSURLErrorDomain Code=-1005 "网络连接丢失。"用户信息=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 看起来像一个 GET 请求字符串,但你想做一个 POST ......(我只是有点困惑)
-
我可以从浏览器成功连接。这应该不重要吧?因为网络连接丢失错误不会被抛出,它会像一个 500 错误。
-
另一件奇怪的事情是,如果我将域设置为 google.com,它可以工作,所以我有点难过。
-
可能您的 url 编码没有正确完成,只需在 urlpath 和 postdata 上尝试 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding(仅供参考,最好将 Content-Length 添加到您的请求中)
-
仍然给出网络连接丢失,但我没有添加Content-Length,不知道在哪里添加它。我还用 stringByAddingPercentEncoding 粘贴了上面更新的代码,只是为了确保我做的一切都是正确的。
标签: php ios objective-c nsurlconnection nsurlrequest