10

我已经检查了与此相关的其他问题,但唯一的答案是“使用ASIHTTPRequest”,因为它不再被开发我想问人们正在使用哪些替代品,在使用我们的 SDK 时我遇到了很多奇怪的行为NSURLConnection从服务器接收数据时。

NSURLConnection我们将其追溯到不能很好地处理分块编码中的响应这一事实。或者至少我们在这里阅读了这个问题NSURLConnection 和“分块”传输编码

我们采访的一些开发人员说它在 iOS 5 中变得更好,我们需要确保我们的 SDK 至少向后兼容 iOS 4.3。

我想确认这实际上是一个问题NSURLConnection,以及人们如何处理它。

到目前为止我发现的所有替代方案都是基于的NSURLConnection,我假设这样会有同样的缺陷。ASIHTTPRequest实际上确实有效,因为它的基础略低于NSURLConnection,但正在寻找不再支持的知识的替代方案。

查看的其他库列表是: Restkit, ShareKit, LRResty, AFNetworking, TTURLRequest

我知道这里有类似的问题RESTKit 是 ASIHTTPRequest 的一个很好的替代品吗?和这里ASIHTTPRequest 替代但是这两种解决方案都基于 NSURLConnection。

编辑:我注意到我在帖子开头指出了错误的问题,所以更新了。它指向 2008 年的一个线程,我见过类似的线程,但没有一个是最近的。

4

3 回答 3

19

NSURLConnection 支持分块传输。我用它们。

  1. 定义一些道具:

    NSMutableData * responseData;
    NSURLConnection * connection;
    
  2. 建立连接

    NSURL *url = [NSURL URLWithString:@"...."];
    self.responseData = [[NSMutableData alloc] initWithLength:0] ;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    
  3. 注册您的回调方法以建立连接

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
         // You may have received an HTTP 200 here, or not...
         [responseData setLength:0];
    }
    
  4. 为“收到的块”注册您的回调方法

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        NSString* aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    
        NSLog(@"This is my first chunk %@", aStr);
    
    }
    
  5. 注册您的“连接完成”回调:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
       [connection release];
    }
    
  6. 最后,注册“连接失败”回调:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Something went wrong...");
}
于 2012-02-27T23:03:07.383 回答
9

只是为了接听下一个到达这里但仍然无法让 NSURLConnection 处理块编码数据的人。

NSURLConnection 将使用分块编码,但具有未公开的内部行为,因此它将在打开连接之前缓冲前 512 个字节,并让任何内容通过响应标头中的 IF Content-Type 为“text/html”或“application/八位字节流”。这至少与iOS7有关。

However it doesn't buffer the response if Content-Type is set to "text/json". So, whoever can't get chunked encoded NSURLConnection responses to work (i.e. callbacks aren't called) should check the response header and change it on the server to "text/json" if it doesn't break application behaviour in some other way.

于 2014-06-12T10:36:54.767 回答
2

我不知道有任何替代方案。

所有其他库都建立在 NSURLConnection 之上。尽管您可以使用其中一个非 iOS 库,例如。库库尔。

ASIHTTPRequest 是我所知道的唯一一个构建在 CFNetworking 层之上的库。这是(可能是间接的)原始开发人员停止工作的主要原因 - 因为它不使用 NSURLConnection 它有很多代码。

说不再支持 ASIHTTPRequest 可能并不完全正确。确实,原来的开发者不再在它上面工作了,但是如果你查看 github 提交,你会发现它仍在被其他人处理。很多人仍然使用它,出于各种原因,包括我自己。

说了这么多,回到你遇到的问题:我不确定一个 3 年的线程是否一定是证明 NSURLConnection 的 1 年旧版本(即 iOS 4.3)不支持分块的明确参考转移。分块传输在网络上被大量使用,以至于它似乎不太可能出现如此大而明显的问题。您正在使用的服务器可能有一些非常特殊的东西导致了问题。

于 2012-02-15T19:42:29.370 回答