AFNetworking http client not sending JSON parameters
-
12-12-2019 - |
Question
I created a subclass of AFHTTPClient
and am trying to send some JSON parameters to a server.
However the server is responding with a Expected content type
{(
"text/json",
"application/json",
"text/javascript"
)}, got application/xml
According to AFNetworking FAQ
If you're using AFHTTPClient, set the parameterEncoding property to AFJSONParameterEncoding. Any method on that HTTP client with a parameters argument will now encode the passed object into a JSON string and set the HTTP body and Content-Type header appropriately.
I've done that here but the server appears not to recognize the content-headers. Does anyone know of a potential solution?
Here is the method:
- (void)getCompanyDataWithString:(NSString*)companySearchQuery
finish:(LBMarkitAPIRequestCompletionBlock)finishBlock
{
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setParameterEncoding:AFJSONParameterEncoding];
NSDictionary *params = [NSDictionary dictionaryWithObject:
companySearchQuery forKey:@"input"];
NSMutableURLRequest *searchQueryRequest = [self requestWithMethod:@"GET"
path:kMarkitCompanyURL parameters:params];
AFJSONRequestOperation *searchRequestOperation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:searchQueryRequest
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json)
{
NSLog(@"Response: %@", response);
NSLog(@"JSON: %@",json);
NSMutableArray *results = [NSMutableArray array];
NSError *anError = [[NSError alloc] init];
if ([json objectForKey:@"Message"])
{
NSString *message = [json objectForKey:@"Message"];
anError = [[NSError alloc] initWithDomain:message
code:100
userInfo:nil];
}
// Need some error handling code here
for (id item in json)
{
NSString *aName = [item objectForKey:@"Name"];
NSString *aSymbol = [item objectForKey:@"Symbol"];
NSString *anExchange = [item objectForKey:@"Exchange"];
LBCompany *aCompany = [[LBCompany alloc] initWithName:aName
Symbol:aSymbol Exchange:anExchange];
[results addObject:aCompany];
}
// Need to run the passed in block after JSON
// Request Operation succeeds
finishBlock(results,anError);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
NSError *error, id JSON)
{
NSLog(@"request failed: %@",[error localizedDescription]);
NSLog(@"Response: %@",response);
NSLog(@"JSON: %@",JSON);
}];
[searchRequestOperation start];
NSLog(@"JSON operation started");
}
Solution
The issue was with URL formatting. I didn't notice an API implementation detail that made sending Query Parameters necessary and also specifying JSON output in the URI.
There were no issues with regard to AFNetworking.