I'm using NSURLConnection sendAsynchronousRequest
to grab a user id from my server using an HTTP post request. Here is the code that I use to do this:
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//....
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"data string: %@", dataString);
//...
}];
When I test the request using Hurl.it to check the raw output, I get a numerical string such as "13729", as expected. However, The NSLog output will return something like this:
data string:
13729
As you can see, two extra line breaks are being added. I can solve this using the following code:
NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
However, I would still like to understand why this is happening. Can someone please explain?
As mentioned in the comments, NSString and NSURLConnection are behaving correctly in this case. The data <0d0a3331 303137>
starts with the UTF-8 characters CR LF
. This is likely due to a server-side bug where the values are getting inserted.
As to why Hurl.it is not displaying that in the raw output, it is probably due to a bug on their end. A normal HTTP response is:
{header1} CR LF
...
{headerN} CR LF
CR LF
{body}
And your response is:
{header1} CR LF
...
{headerN} CR LF
CR LF
CR LF
{body}