Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone URL Request: Add value to HTTP header field

I'm trying to add a value to the header for a URL request.

Something like this works just fine:

[urlRequest addValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];

But this doesn't even show up in the header:

NSString *authString = [[NSString alloc] initWithString:
                          [defaults objectForKey:@"auth"]];
[urlRequest addValue:authString forHTTPHeaderField:@"iphoneID"];

I'm completely stumped. The auth string is around 90 characters long. Is this a problem?

Edit: Here's the code I'm trying:

NSString *authString = [[NSString alloc] initWithString:[defaults objectForKey:@"auth"]]; 
[urlRequest addValue:authString forHTTPHeaderField:@"iphoneid"]; 
[urlRequest addValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"]; 

I can see the Accept-Encoding header being sent through Wireshark, but iphoneid is nowhere to be found. It's just a string, 80-90 characters long.

Another Update: So it seems that the problem isn't the field "iphoneid" but rather the authString I'm trying to pass into it. Other strings that I just create with the @"something" work fine, but the auth string that I pull from NSUserDefaults doesn't appear.

Suggestions on how to debug this?

like image 520
Michael Grinich Avatar asked Apr 26 '09 22:04

Michael Grinich


2 Answers

The true problem.

The string I was pulling from NSUserDefaults already had a line ending. When set as a header, another \r\n is appended, which apparently isn't valid. Thus, the header wouldn't appear in any outgoing packets.

The fix:

Use this to trim off the characters before setting as a header value.

[yourString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

like image 112
Michael Grinich Avatar answered Sep 18 '22 02:09

Michael Grinich


Testing checklist:

  • Verify that you actually have a NSMutableURLRequest (and not a NSURLRequest) at this point. In particular, check your logs for an exception due to "unrecognized selector."

  • Verify that urlRequest is not nil.

  • Switch to setValue:forHTTPHeaderField: rather than addValue:forHTTPHeaderField:.

  • Swap the forHTTPHeaderField: value to @"Accept-Encoding" to see if the field is the problem

  • Swap @"gzip" for auth to see if the value is the problem.

like image 31
Rob Napier Avatar answered Sep 19 '22 02:09

Rob Napier