使用IOS5发出HTTPGET请求的最简单方法是什么



我正试图将建议从我的应用程序发送到我的web服务器上的php文件,我已经在浏览器中测试了php脚本,该脚本会向用户发送电子邮件并将建议存储在我的数据库中,一切都很好。。当运行以下脚本时,我通过IOS成功连接,但我在数据库中没有收到结果。。

NSString *post = [NSString stringWithFormat:@"http://blahblah.com/suggest.php?s=%@&n=%@&e=%@", suggestion, name, email];
    // Create the request.
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:post]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    // create the connection with the request
    // and start loading the data
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        NSLog(@"Connection establisted successfully");
    } else {
        NSLog(@"Connection failed.");
    }

我已经检查了所有的字符串,并用%20等对所有空格进行了编码。有人能看到我的脚本不起作用的明显原因吗?

在不打开safari的情况下,从我的应用程序发出HTTP请求的最简单方法是什么?

问题是您正在创建连接,但没有发送实际的"连接"请求。代替

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

尝试使用以下代码:

NSURLResponse* response = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil]

这是一个快速而肮脏的解决方案,但请记住,当这个连接正在进行时,您的UI线程将看起来被冻结。解决方法是使用异步连接方法,该方法比上面的方法稍微复杂一些。在web上搜索NSURLConnection发送异步请求-答案就在那里。

最新更新