user3606054
user3606054

Reputation: 591

Having trouble sending requests using AFNetWorking

It seems that AFNetworking isn't working correctly for me. Specifically when I send apiKey request to server it gives me an unauthorized error. ASIHTTPRequest works fine for me however, so there seems to be something I am doing wrong in AFNetWorking. I know the problem is sending apiKey because if I comment it out AFNetWork works correctly. I still need to send the API key however. Any help will be appreciated.

AFNetWorking

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:apiKey forHTTPHeaderField:@"apiKey"];
NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
[manager POST:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    [operation setUserInfo:userinfo];  
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [operation setUserInfo:userinfo];
}];
}

ASIHTTPRequest

  NSString *urlStr = [NSString stringWithFormat:@"%@/%@", submitReportUrl, [self urlEncode:path]];
 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
 [request setDelegate:self];
 NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
 [userinfo setObject:NSStringFromSelector(self.didFinishSelector) forKey:@"didFinishSelector"];
 [userinfo setObject:NSStringFromSelector(self.didFailSelector) forKey:@"didFailSelector"];
 [request setUserInfo:userinfo];
 [request addRequestHeader:@"apiKey" value:apiKey];
 [request setRequestMethod:method];
  NSArray *keys = [params allKeys];
  for ( NSString *key in keys )
        [request addPostValue:[params objectForKey:key] forKey:key];
 [self.operationQueue addOperation:request];

Upvotes: 2

Views: 249

Answers (1)

Dipu Rajak
Dipu Rajak

Reputation: 693

manager.requestSerializer = [AFJSONRequestSerializer serializer]; 

I had the same problem working with the post. So research where was the problem. If you did not add the about line of the code. AFNetworking will automatically add in the header

Content-Type : "text/html" either one Cotent-Type : "text/plain"

By adding above code becomes Content-Type : "application/json"

So the problem is solved. Since the server is expecting JSON.

Upvotes: 1

Related Questions