Search code examples
iosnsurlconnectionnsmutableurlrequest

setValue:@"application/json" forHTTPHeaderField:@"Content­-Type" Not Working


Simple as it is:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:linkURLString]];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:10];
[request setValue:@"application/json" forHTTPHeaderField:@"Content­-Type"];
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:nil]];

If I log the value for the header @"Content­-Type" I got nil. And that what I got at the backend. Every other value is set and even tried other header fields, works fine!. I tried setting the body before the header and still got nil.


Solution

  • I tried to copy and paste your code and I obtained (null) as well.

    By printing the list of all HTTPHeaderFields ([request allHTTPHeaderFields]) I got:

    Content-Type: {
        "Content\U00ad-Type" = "application/json";
    }
    

    As you see, there is a strange Unicode character: \U00ad. This is the reason why when you try to get the value associated with Content-Type, it finds null.

    So I tried to reolace the string @"Content-Type" in your code, and the result was:

    Content-Type: {
        "Content-Type" = "application/json";
    }
    

    And indeed now, logging:

    NSLog(@"Content-Type: %@", [request valueForHTTPHeaderField:@"Content-Type"]);
    

    I obtained:

    Content-Type: application/json