Mostafa Sultan
Mostafa Sultan

Reputation: 2438

AFNetworking send header with request

I have been searching for hours and found answers like this : but when i send the Authorization like this :

    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //header = [header stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

        //[manager.requestSerializer setValue:@"text/json" forHTTPHeaderField:@"Accept"];
        //[manager.requestSerializer setValue:@"text/json" forHTTPHeaderField:@"Content-Type"];
        [manager.requestSerializer setValue:header forHTTPHeaderField:@"Authorization"];
        /*
        NSLog(@"headers: %@",manager.requestSerializer.HTTPRequestHeaders);
        this printed : {
            "Accept-Language" = "en;q=1";
            Authorization =  "Bearer eyJ0eXAiO";
            "User-Agent" = "Virtuocity/1.0 (iPhone; iOS 10.2; Scale/2.00)";
        }
        */
        [manager GET:url parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            block(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            block(nil,error);
        }];

but the server gave me the following error:

serialization.response Code=-1011 "Request failed: unauthorized (401)  headers {
    "Access-Control-Allow-Headers" = "accept, accept-language, content-type, accept, authorization, moduleid, tabid, x-dnn-moniker";
    "Access-Control-Allow-Methods" = "GET, POST, PUT, HEAD, OPTIONS";
    "Access-Control-Allow-Origin" = "*";
    "Cache-Control" = "no-cache";
    "Content-Length" = 61;
    "Content-Type" = "text/json; charset=utf-8";
    Date = "Sun, 29 Jan 2017 10:18:36 GMT";
    Expires = "-1";
    Pragma = "no-cache";
    "Set-Cookie" = "dnn_IsMobile=False; path=/; HttpOnly, dnn_IsMobile=False; path=/; HttpOnly, language=en-US; path=/; HttpOnly";
}

i observed that the returned headers from the error don't include the 'Authorization' header i sent them , and i doubt that is because of the white space sent in the header so i don't know what is wrong and i tried the same request on POST MAN and worked perfectly so what to do now ?

Upvotes: 0

Views: 1232

Answers (1)

Mostafa Sultan
Mostafa Sultan

Reputation: 2438

I Found out that AFNetworking is sending some sort of cookies by default and the api i am dealing with won't check for Authorization if there are cookies to check so i disabled sending cookies with this line and it worked ^__^

[manager.requestSerializer setHTTPShouldHandleCookies:NO];

Upvotes: 1

Related Questions