ios - URLConnection sendSynchronousRequest 问题?

标签 ios web-services

我正在对 Web 服务进行同步调用,有时我会从 Web 服务返回正确的结果,有时我会收到指示运行时错误的 HTML 结果。在 iOS 端我必须做些什么才能正确调用网络服务。这是我的代码:

NSURLResponse *response = nil; 
NSError *error = nil;         
NSString *requestString = @"some parameters!";        
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];        
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];

NSData *data = [NSURLConnection sendSynchronousRequest:request 
                                     returningResponse:&response 
                                                 error:&error];    
NSString *responseData = [[NSString alloc] initWithData:data 
                                               encoding:NSUTF8StringEncoding];

是不是我发布不当?

最佳答案

你必须像这样设置 urlconnection 的委托(delegate)方法

NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
 [urlRequest setHTTPMethod:@"POST"];
 urLConnection=[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

下面的委托(delegate)方法可以解决问题

    - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    [receivedData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  
{

    [receivedData appendData:data];

}  

如果连接失败,您将在以下委托(delegate)中收到错误

  - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{}

你最好从已完成的连接中得到响应,它告诉你所有数据都已收到

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection  
{  
recievedData //the complete data 
}

关于ios - URLConnection sendSynchronousRequest 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7435537/

相关文章:

ios - 当我尝试获取 Realm 0.96.2 时 pod install 不起作用

c++ - 生成没有 stub 的 WSDL 请求/响应

rest - WebSphere Application Server/8.0/Uncaught 由 servlet 创建的初始化异常

web-services - 使用纯 JAX-WS 添加 SOAP header 对象

ios - 如何在Objective-C中传递2个参数

ios - 弹出 View Controller 时应用程序崩溃

ios - 如何限制我的应用程序仅适用于 iPhone

objective-c - Facebook SDK : ActiveSession is still closed after I give permission

javascript - 从现有的 sqlite 数据库中获取数据到网页中

ios - 更新到XE2 Update 2后,Delphi/FPC代码不再在XCode下编译