ASIHTTPRequest: incorrect NSStringEncoding value 0

2020-06-25 04:15发布

问题:

Incorrect NSStringEncoding value 0x0000 detected. Assuming NSStringEncodingASCII. Will stop this compatiblity mapping behavior in the near future.

When I was using ASIHTTPRequest, I keep getting this error(50% of the times), what's wrong with it?

I assume the URL I passed in is correct, as it does not contain any space or strange character, maybe it is the result string having some unrecognized character?

回答1:

Copying my answer from https://stackoverflow.com/q/8251175/918764

The error is not that your data isn't encoded correctly, it's almost certainly that you're requesting some kind of string data from an ASIHTTPRequest object that doesn't have an encoding set yet - this will happen if the request failed to connect to the server, or if the server didn't send an understandable encoding header.


This notably happens if you call [asiHttpRequest getResponseString] before a valid response has been returned and the request encoding has been set (i.e. couldn't connect to server).

The easiest way to workaround this warning is by editing the ASIHTTPRequest class, remove the @synthesize responseEncoding and adding a simple custom getter/setter so you can return the default encoding if the response encoding isn't set:

- (NSStringEncoding) responseEncoding
{
    return responseEncoding || self.defaultResponseEncoding;
}

- (void) setResponseEncoding:(NSStringEncoding)_responseEncoding
{
    responseEncoding = _responseEncoding;
}

There's also a more specific workaround for the getResponseString method, which I think is the only place that uses the encoding without checking for a value - since the encoding should be set for any non-zero length response:

- (NSString *)responseString
{
    NSData *data = [self responseData];
    if (!data) {
        return nil;
    }
    // --- INSERT THIS BLOCK ---
    // If the 'data' is present but empty, return a simple empty string
    if (data.length == 0) {
        return @"";
    }
    //assert(self.responseEncoding); // if you're into runtime asserts, uncomment this
    // --- END OF BLOCK TO INSERT ---
    return [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:[self responseEncoding]] autorelease];
}