Search code examples
iosiphonejsonpostafnetworking-2

iOS Get JSON response from AFNetworking HTTP POST method with JSON parameters


I am getting a 404 error while posting with JSON parameters at the https://api.hackerearth.com/codemonk/v1/topic­detail/. The server uses POST HTTP method to get a topic's details & JSON response is expected when successful. The POST parameter is id of the topic object. POST Parameters are expected to be in JSON. I am using AFNetworking as follows -

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

NSDictionary *params = [NSDictionary dictionaryWithObject:@1 forKey:@"id"];

NSString *str = @"https://api.hackerearth.com/codemonk/v1/topic­-detail/";

NSString *encodedStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[manager POST:encodedStr
   parameters:params
      success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

    NSLog(@"responseObject : %@",responseObject);


} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {

    NSLog(@"error : %@", error.localizedDescription);

}];

This is regular stuff but don't know why I can't seem to get it correct now. I am only getting a 404 Page Not Found error. This is not a server side issue for sure. Any help guys ?


Solution

  • Maybe this will help.

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
    
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    operationManagerInstance.requestSerializer = requestSerializer;
    

    =============UPDATE

    I have 404 when copying your URL. It's because hyphen symbol between topic-detail is not actually hyphen. It's some special character that doesn't work.

    https://api.hackerearth.com/codemonk/v1/topic­-detail/

    Instead I deleted it and typed hyphen manually and it works fine.