SDK and AFNetworking - ios

I am trying to write code for an SDK. I need to make API calls.
I am using AFNetworking 2.0 to send a POST request to the server:
NSDictionary * params = [self formDictionaryFromCard: card];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString: [self apiUrl] parameters: params];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"Firefox" forHTTPHeaderField:#"User-Agent"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
successBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
errorBlock(error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
So far I have the above, but I can't figure out how to pass in headers (like the authorization header), or provide support for https.
Can anyone please help?
Also how can I know what http status code was returned?

Related

AFNetworking POST non JSON String

I am trying to create a POST request by using AFNetworking library.
[self.manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id response)
{
// CODE
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
// CODE
}];
Is there a way to post a simple string (not a JSON one) as a request body parameters by using AFNetworking?
Yes this is how you do it:
NSString *someString = #"SomeString";
NSData* stringData = [someString dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"someUrlString"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: stringData ];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//Success Block
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure Block
}];
[op start];

AFNetworking How to send a string of post request?

AFNetworking How to send a string of post request?
//restrinBASE64STRING is a NSString ,Program error
[manager POST:URLString parameters:restrinBASE64STRING success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Solve the problem
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:URLString]];
[request setHTTPMethod:#"POST"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[restrinBASE64STRING dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[[NSOperationQueue mainQueue] addOperation:operation];

AFNetworking NTLM Authentication not getting records

I have a web service which when hit on web browser asks for username and password. I have to integrate same web service in my mobile app.
I searched a lot and got link which helps in implementing NTLM Authentication via AFNetworking.
Now under success block I am not getting response data. I am getting 0 records.
Success: {"records":[]}
Whereas hitting service on web browser I get all the records.
below is my code
NSString *str = #"complete web service url";
NSString *encode = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSURLCredential *credential = [NSURLCredential credentialWithUser:#"userName" password:#"password" persistence:NSURLCredentialPersistenceNone];
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:#"GET" URLString:encode parameters:nil error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCredential:credential];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", [operation responseString]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[manager.operationQueue addOperation:operation];
Can anyone help me please that what is causing the problem. Thanks in advance.

AFNetworking: How to convert this header request to use AFNetworking?

I have the following code below that uses a rather old library called ASIHTTPRequest. I am looking to upgrade the library, but need a little help to make sure I am doing it correctly and to get my feet wet. This is the code I need to convert to AFNetworking. Any tips or suggestions is appreciated.
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 setUserAgentString:USER_AGENT];
[request setTimeOutSeconds:60];
[request addRequestHeader:#"apiKey" value:apiKey];
[request setRequestMethod:method];
With AFNetworking the code should look like below
NSDictionary *parameters=#{"key":value};//The values you want to POST arrange in dictionary.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:apiKey forHTTPHeaderField:#"apiKey"];
[manager.requestSerializer setValue:USER_AGENT forHTTPHeaderField:#"User-Agent"];
[manager.requestSerializer setTimeoutInterval:60];
[manager POST:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Result %#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error.description);
}];
I hope it helps. Cheers.

AFNetworking version 2 content-type error

I'm attempting to make an iphone app that will interact with a particular JIRA server. I've got the following code to log in:
NSURL *url = [[NSURL alloc] initWithString:#"https://mycompany.atlassian.net/rest/auth/latest/session/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"{\"username\":\"%#\",\"password\":\"%#\"}", username, password];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept" ];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"ERROR: %#", error);
}
];
[operation start];
But it's giving me the following error having to do with Content-Type:
ERROR: Error Domain=AFNetworkingErrorDomain Code=-1011
"Request failed: unsupported media type (415)"
UserInfo=0x8cd6540
{
NSErrorFailingURLKey=https://mycompany.atlassian.net/rest/auth/latest/session/,
NSLocalizedDescription=Request failed: unsupported media type (415),
NSUnderlyingError=0x8c72e70
"Request failed: unacceptable content-type: text/html",
I'm not sure what the problem is. I found this question, which I thought might be a similar problem, but the answers say to either use the AFJSONRequestOperation class (which I can't because I'm using AFNetworking version 2, which doesn't have that class), or to fix it on the server side (which I also can't for obvious reasons).
What can I fix this error when I can't fix the server side and I can't use AFJSONRequestOperation?
If using AFNetworking 2.0, you can use the POST method, which simplifies this a bit:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = #{#"username":username, #"password":password};
[manager POST:#"https://mycompany.atlassian.net/rest/auth/latest/session/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
This does the creation of the request, setting its Content-Type according to the requestSerializer setting, and encodes the JSON for you. One of the advantages of AFNetworking is that you can get out of the weeds of constructing and configuring NSURLRequest objects manually.
By the way, the "Request failed: unacceptable content-type: text/html" error means that regardless of what you were expecting to receive (e.g. JSON), you received HTML response. This is very common: Many server errors (e.g. the server informing you that the request was malformed, etc.) generate HTML error messages. If you want to see that HTML, in your failure block, simply log the operation.responseString.
It turns out the problem is that this one line:
[request setValue:#"application/json" forHTTPHeaderField:#"Accept" ];
Should be
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type" ];
The error is now solved. (Edit: I should have both, see CouchDeveloper's comment.)
EDIT
Rob's solution is better, so I'm going with it. I had actually tried a similar solution to what he shows, but where he had the line,
manager.requestSerializer = [AFJSONRequestSerializer serializer];
I had the line:
[manager.requestSerializer
setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
...which didn't work. Kudos to Rob for getting it to work!
I had the same problem in AFNetworking 2.0 and the solution was that I had to make sure I set the AFHTTPRequestSerializer type (In case your request is JSON) the it should be like this.
AFHTTPSessionManager *myHTTPManager = ...
[myManager setRequestSerializer:[AFJSONRequestSerializer serializer]];
You have to set both AFHTTPResponseSerializer and AFHTTPRequestSerializer
if you are using default written class AFAppDotNetAPIClient and you face this error. Must add responseSerializer. see your shared method should look like -
+ (instancetype)sharedClient {
static AFAppDotNetAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[AFAppDotNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:AFAppDotNetAPIBaseURLString]];
_sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
_sharedClient.responseSerializer = [AFHTTPResponseSerializer serializer];
});
return _sharedClient;}
Use this line of code.
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];

Resources