简体   繁体   English

NSURLConnection 将随机字符附加到响应中

[英]NSURLConnection appends random characters to the response

At one place in my app, I initialize an asynchronous request using NSURLConnection:在我的应用程序的一个地方,我使用 NSURLConnection 初始化了一个异步请求:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[self.URLs objectForKey:@"API URL"]]
    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
apiConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];

and fetch the result:并获取结果:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if (responseData == nil) {
        responseData = [[NSMutableData alloc] init];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
    NSLog(@"%s", [data bytes]);
}

The problem is that sometimes random data is being appended to the actual data returned by the server.问题是有时随机数据会附加到服务器返回的实际数据中。 Sometimes, the log message as well as the actual output (after conversion to a NSString object in connectionDidFinishLoading:connection ) contain some part of some header, "CFNetwork" or just arbitrary bytes/characters.有时,日志消息以及实际的 output(在connectionDidFinishLoading:connection中转换为 NSString object 后)包含某些 Z099FB995346F31C749F6E40DB0F395 的某些部分或任意字节/E。

Is this a known bug?这是一个已知的错误? Has anyone encountered this before and knows how to work around this?有没有人遇到过这个问题并且知道如何解决这个问题? Is there anything I might be doing wrong?有什么我可能做错了吗?

You need to append '0' character to limit the string if you use it as an c-String (null terminator).如果将字符串用作 c 字符串(空终止符),则需要 append '0' 字符来限制字符串。

From one of my projects:从我的一个项目中:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   char temp[] = {0};
   [receivedData appendBytes:temp length:1];

   // etc your usual code here
}

Gave me a lot of headaches, too.也让我头疼。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM