How to add custom header to AFNetworking on a JSONRequestOperation - ios

Hi, I have the following code accessing a URL:
NSString * stringURL = [NSString stringWithFormat:#"%#/%#/someAPI", kSERVICE_URL, kSERVICE_VERSION];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]];
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
completionHandler(JSON, nil);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
completionHandler(nil, error);
}];
But I want to pass the user token as a parameter on HEADER, like X-USER-TOKEN.
Cant find it on AFNetworking documentation, should I change the operation type?

Use AFHTTPClient or subclass it!
You can set default headers with -setDefaultHeader:value: like this :
[self setDefaultHeader:#"X-USER-TOKEN" value:userToken];
You can check the documentation

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue: #"X-USER-TOKEN" forHTTPHeaderField:#"< clientToken >"];
[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]

I did this :)
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Token token=\"%#\"", _userObj.oAuth] forHTTPHeaderField:#"Authorization"];

If you have a layer of abstraction, let's say APIManager,
then you should do the following inside a particular method
[[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:#"X-Register"];

Related

AFNetworking, getting 401 with proper token

I'm making a request on https://www.ez-point.com/api/v1/ezpoints with a proper token using a Chrome Rest Client. I'm properly getting the result. However, when using AFNetworking, I'm getting a 401.
Here is my code snippet:
NSURL *url = [[NSURL alloc] initWithString:#"https://www.ez-point.com/api/v1/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url ];
[httpClient setAuthorizationHeaderWithToken:#"xxxxxxxxxx"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET" path:#"/ezpoints" parameters:nil];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#", #"success");
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", #"Error");
Here is the error:
2013-10-29 08:51:38.908 EZ-POINT[4944:c07] I restkit:RKLog.m:34 RestKit logging initialized...
2013-10-29 08:51:39.189 EZ-POINT[4944:c07] I restkit.network:RKObjectRequestOperation.m:180 GET 'https://www.ez-point.com/ezpoints'
2013-10-29 08:51:41.908 EZ-POINT[4944:c07] E restkit.network:RKObjectRequestOperation.m:209 GET 'https://www.ez-point.com/ezpoints' (401 Unauthorized) [2.7191 s]: Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 401" UserInfo=0x1052ef40 {AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest https://www.ez-point.com/ezpoints>, NSErrorFailingURLKey=https://www.ez-point.com/ezpoints, NSLocalizedDescription=Expected status code in (200-299), got 401, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xac54520>}
2013-10-29 08:51:41.908 EZ-POINT[4944:c07] Error
Its working with the following code:
NSURL *url = [[NSURL alloc] initWithString:#"https://www.ez-point.com/api/v1/ezpoints"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:#"4f62fab9c91c46ad971cc2ae4a32bb6f" forHTTPHeaderField:#"Authorization"];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#",[JSON objectForKey:#"status"]);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", #"Error");
}];
[operation start];

AFNetworking getting HTML from rails

I am using AFNetworking to get JSON data from the server, but I am only getting back HTML and an error that says the following:
Expected content type {(
"text/json",
"application/json",
"text/javascript"
)}, got text/html, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x7592470>}
The code is as follows:
NSURL *url = [NSURL URLWithString:#"http://127.0.0.1:3000/games"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *req, NSHTTPURLResponse *response, id jsonObject){
NSLog(#"Response: %#", jsonObject);
}
failure:^(NSURLRequest *req, NSHTTPURLResponse *response, NSError *error, id jsonObject){
NSLog(#"Error: %#", error);
}];
[operation start];
I am using rails and the server sends back JSON when I access the page with curl. I want to force application/json to be requested, am I doing this wrong?
You probably need to tell the server what content type you want back.
Here's a common fix for this issue:
NSURL *url = [NSURL URLWithString:#"http://127.0.0.1:3000/games"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
If this doesn't work, you'll need to step through your server code to determine under what conditions it'll return JSON instead of HTML.

AFNetworking application/json

Using iOS, I'm trying to communicate with a webservice that requests 3 headers followed by JSON POST data.
I've taken a look at the following AFNetworking snippet which converts a Dictionary to a JSON file. In this case I'm trying to POST both the headers and a JSON file. Let me know if you have any suggestions:
NSURL *url = [NSURL URLWithString:WalletKit_URL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFJSONParameterEncoding;
NSDictionary *params = #{#"brand-id" : Brand_Id, #"api-key" : API_Key, #"Content-Type" : #"application/json"};
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"" parameters:params];
AFHTTPRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSURLResponse *response, id JSON) {
NSLog(#"success");
} failure:^(NSURLRequest *request, NSURLResponse *response, NSError *error, id JSON) {
NSLog(#"error");
}];
You should add the HTTP header fields to the NSMutableURLRequest.
[request addValue:#"foobar" forHTTPHeaderField:#"X-Foo-Bar"];

Error with AFNetworking for JSON Parsing

I have the following code for JSON Parsing:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://www.dropbox.com/s/qz16qyi3julygl9/facebook.json"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Request Success %#",[JSON class]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failure Because %#",[error userInfo]);
}];
[operation start];
but I have Request Failure with the following error message:
NSErrorFailingURLKey = "https://www.dropbox.com/s/qz16qyi3julygl9/facebook.json";
NSLocalizedDescription = "Expected content type {(\n \"text/json\",\n \"application/json\",\n \"text/javascript\"\n)}, got text/html";
can somebody help me?
In my errorlog it prints "got text/html". So just add
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:#"text/html"]]
It works.
[AFJSONRequestOperation addAcceptableContentTypes:#"text/plain"]
The above is deprecated from AFNetworking 2.x. Instead you can call the following on the instance of the AFHTTPRequestOperation as follows
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/plain"];
Where manager is your instance of AFHTTPRequestOperation.
Source: https://github.com/AFNetworking/AFNetworking/issues/1381
Because the link you provide doesn't hotlink the file. It links to an HTML page to download the file. Try going there in a browser...
Try this link instead: https://dl.dropbox.com/s/qz16qyi3julygl9/facebook.json?dl=1 No guarantees it will work though. A lot of companies frown on directly linking to files in this way.

AFNetworking + AFJSONRequestOperation + Rails

I'm using NSMutableURLRequest before using AFJSONOperationRequest and I have a problems getting the data in my Rails app.
If I use :
NSMutableURLRequest *request = [[HTTPClient sharedClient] multipartFormRequestWithMethod:#"POST" path:path parameters:dict constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
}];
Then :
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
else {
}
}
I get my data correctly formatted in the Rails logs:
Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}
But I don't need AFMultipartFormData to send a file... (no file to send)
So, instead, I use:
NSMutableURLRequest *request = [[HTTPClient sharedClient] multipartFormRequestWithMethod:#"POST" path:path parameters:dict];
with my AFJSONRequestOperation too. But, my parameters are now not set correctly in my rails app:
Parameters: {contact[country_id] => "45", contact[lastname] => "Tutu"}
instead of
Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}
I don't understand why. It looks like the body of the request is not set correctly when I don't use the block: "constructingBodyWithBlock".
Don't use multipartFormRequestWithMethod.
Just use the postPath method like this
[[YourHTTPClient sharedClient] postPath:path
parameters:dict
success:^(AFHTTPRequestOperation *operation, NSString* path){
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Edit:
If you need an operation use AFJSONRequestOperation directly
+ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
NSURL *url = [NSURL URLWithString:#"http://yoursite.com/path"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];

Resources