request auhtorization failed 401 - afnetworking-2

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSString *URLString = #"http://52.201.233.32:1337/login";
NSURL*url=[NSURL URLWithString:URLString];
NSDictionary *parameters = #{#"email":#"one_user#gmail.com", #"password":#"asdfasdf"};
NSMutableURLRequest*request=[[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:URLString parameters:parameters error:nil];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
[[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:URLString parameters:parameters error:nil];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Error" message:error.localizedDescription preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
} else {
NSArray *responseArray = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%# ----->%#", response, responseArray[0][#"email"]);
self.fullarray = responseArray[0][#"email"]; }
}];
[dataTask resume];

Related

Obj-C POST JSON (body?)to endpoint problems

Using Postman on my Mac I have confirmed GET/POST works to my endpoint. On my iPad I am trying to do the same thing but only GET connects and returns data (just for
testing).
In Postman I have key of devices and value of [{"name":"1","values":[121,182,243]}]
From Postman I can Send and the physical object responds and the server returns an array of all devices and nothing else (which I do not require but that is how it goes). Postman does have x-www-form-urlencoded under Body. This works as expected from Postman.
From my iPad the following code always returns an error 400 which I think means I am providing something the server is not expecting.
+(void)makeRequest {
NSError *error = nil;
storedURL = [[NSUserDefaults standardUserDefaults] objectForKey:#"eb-ipaddress-saved"];
NSString *urlstring = [NSString stringWithFormat:#"http://%#",storedURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString *jsonPostBody = #"{\"devices\":[{\"name\":\"1\",\"values\":[121,182,243]}]}";
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"SUCCESS");
}
else
{
NSLog(#"FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];
}
My 4 logs from above (removed for clarity) return:
urlstring http://192.168.90.55:3000/dmx/set
jsonPostBody {"devices":[{"name":"1","values":[121,182,243]}]}
httpResponse 400
Error
I will eventually switch to variables in my POST when in production.
Thank you
Thanks to Larme's answer I used the code from Postman and that worked.
+(void)makeRequest
{
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.90.55:3000/dmx/set"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSDictionary *headers = #{
#"Content-Type": #"application/x-www-form-urlencoded"
};
[request setAllHTTPHeaderFields:headers];
NSMutableData *postData = [[NSMutableData alloc] initWithData:[#"devices=[{\"name\":\"1\",\"values\":[121,182,243]}]" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postData];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
dispatch_semaphore_signal(sema);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"%#",responseDictionary);
dispatch_semaphore_signal(sema);
}
}];
[dataTask resume];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

Invalid type in JSON write (NSConcreteMutableData)

I am trying to send a JSON request with AFNetworing but following code giving me JSON text did not start with array or object and option to allow fragments not set error:
NSString *post = [[NSString alloc] initWithFormat:
#"{\"request\":\"login\",\"userName\":\"%#\",\"password\":\"%#\"}", userName, password];
NSData *parameters = [post dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *parameterDictionary =
[NSJSONSerialization JSONObjectWithData:parameters options:NSJSONReadingAllowFragments error:nil];
DDLogDebug(#"Data: %#", [parameterDictionary description]);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager POST:WEB_SERVICE_URL parameters:parameterDictionary
success:^(AFHTTPRequestOperation *operation, id responseObject) {
DDLogDebug(#"LoginView - Success Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError(#"LoginView - Error Response: %#", [error description]);
}];
[operation start];
This is the log output of the parameterDictionary object:
{
password = q;
request = login;
userName = q;
}
I have looked similar questions for the error and tried to put parameters object in to an array but this time I got the error "Invalid type in JSON write (NSConcreteMutableData)"
NSMutableArray *array = [NSMutableArray new];
[array addObject:parameterDictionary];
DDLogDebug(#"Data: %#", [parameterDictionary description]);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager POST:WEB_SERVICE_URL parameters:array
success:^(AFHTTPRequestOperation *operation, id responseObject) {
DDLogDebug(#"LoginView - Success Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError(#"LoginView - Error Response: %#", [error description]);
}];
What I am doing wrong?
UPDATE:
I have tried following but it did't work:
NSMutableDictionary *dictionary = [NSMutableDictionary new];
[dictionary setObject:#"login" forKey:#"request"];
[dictionary setObject:#"q" forKey:#"userName"];
[dictionary setObject:#"q" forKey:#"password"];
DDLogDebug(#"Dictionary: %#", [dictionary description]);
DDLogDebug(#"Json: %#", [dictionary JSONRepresentation]);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
AFHTTPRequestOperation *operation =
[manager POST:WEB_SERVICE_URL parameters:dictionary
success:^(AFHTTPRequestOperation *operation, id responseObject) {
DDLogDebug(#"LoginView - Success Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError(#"LoginView - Error Response: %#", [error description]);
}];
UPDATE 2:
This what my AFHTTPRequestOperation look like on error block:
<AFHTTPRequestOperation: 0x7fd881fa1200, state: isFinished, cancelled: NO request: <NSMutableURLRequest: 0x7fd881f9fd60> { URL: http://www.olcayertas.com/services.php }, response: <NSHTTPURLResponse: 0x7fd881d913b0> { URL: http://www.olcayertas.com/services.php } { status code: 200, headers {
Connection = close;
"Content-Length" = 1050;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 21 Jan 2015 10:28:45 GMT";
Server = Apache;
"X-Powered-By" = PleskLin;
} }>
The JSON does not seem to validate on JSONlint.com. I would make sure the JSON is correct from there first.
This is what I entered:
{\"request\":\"login\",\"userName\":\"%#\",\"password\":\"%#\"}
I use this to check the JSON:
if ([NSJSONSerialization isValidJSONObject:requestJSONContents]) { }
I have solved the problem by checking my web service in browser. The problem was in my services.php file. There was an error about log file creation and this error was returning a non JSON response that causing the request to fail. My complate working code is here:
NSMutableDictionary *dictionary = [NSMutableDictionary new];
[dictionary setObject:#"login" forKey:#"request"];
[dictionary setObject:#"q" forKey:#"userName"];
[dictionary setObject:#"q" forKey:#"password"];
DDLogDebug(#"Dictionary: %#", [dictionary description]);
DDLogDebug(#"Json: %#", [dictionary JSONRepresentation]);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
//[manager.securityPolicy setAllowInvalidCertificates:true];
AFHTTPRequestOperation *operation =
[manager POST:WEB_SERVICE_URL parameters:dictionary
success:^(AFHTTPRequestOperation *operation, id responseObject) {
DDLogDebug(#"LoginView - Success Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError(#"LoginView - Error Response: %#", [error description]);
DDLogError(#"Error: %#",operation);
}];
[operation start]
And here is my complate services.php file to make it as a complate example for passing and getting JSON with AFNetworiking and PHP service:
PHP web service that accepts JSON input and return JSON response

Passing param in URL to get json back in IOS

Sorry i am really beginner in IPhone development,i am pulling json data from URL and its pulling and loading data perfectly in UITableView, below is code
- (void)fetchFeed
{
NSString *requestString = #"http://bookapi.bignerdranch.com/courses.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
self.session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.courses = jsonObject[#"courses"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}];
[dataTask resume];
}
Now i want to add filter by instructors, Can any one tell me how i can do that.
Thanks
GET
GET request is just a matter of appending query strings to the API url, for example:
NSString *format = [NSString stringWithFormat:#"http://www.yourapiurl.com?id=%#","123";
NSURL *url = [NSURL URLWithString:format];
NSLog(#"%#",url);
//Creating the data object that will hold the content of the URL
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
POST
-(NSData *)post:(NSString *)postParams{
//Build the Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.yourapiurl.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postParams length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postParams dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
return returnData;
}
usage:
NSString *postString = [NSString stringWithFormat:#"prop1=%#&prop2=%#&prop3=%#",
"value1","value2","value3"];
NSData *JsonData = [self post :postString];
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:JsonData options:NSJSONReadingMutableContainers error:nil];
//then parse the JSON

JSON params POST not recognize with AFNetworking

[Solved]
I'm trying to edit AFHTTPClient.m to make it work with POST Method in
-(NSMutableURLRequest *)requestWithMethod:(NSString *)method
path:(NSString *)path
parameters:(NSDictionary *)parameters
like this :
if ([method isEqualToString:#"GET"] ||[method isEqualToString:#"POST"] || [method isEqualToString:#"HEAD"] || [method isEqualToString:#"DELETE"])
I have problem with POST method with params userDevice ,I have function subclass from AFHTTPClient like this
EDIT:
I used different method like this but same result
-(void)loginWithEmail:(NSString *)email password:(NSString *)passwords
{
NSString *baseurl = #"http://localhost.com:9000/";
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:baseurl]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
[httpClient setAuthorizationHeaderWithUsername:email password:passwords];
and then this is my params :
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
model, #"deviceModel",
systemVersion, #"deviceVersion",
[NSNumber numberWithBool:0], #"productionMode",
appVersion, #"appVersion",
deviceType,#"deviceType", nil];
NSError *error = nil;
NSDictionary* jsonObject = [NSDictionary dictionaryWithObjectsAndKeys:data, #"userDevice", nil];
NSData *jsonLogin =[NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonLoginString = [[NSString alloc] initWithData:jsonLogin encoding:NSUTF8StringEncoding];
NSLog(#"JSON LOGIN OUTPUT :%#", jsonLoginString);
[httpClient setParameterEncoding:AFJSONParameterEncoding];
I request using this code :
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"/ios/login"
parameters:[NSDictionary dictionaryWithObjectsAndKeys:jsonLoginString,#"userDevice", nil]
];
AFJSONRequestOperation *operation = nil;
operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Response : %#", request);
NSLog(#"JSON: %#",JSON);
}
failure:^(NSURLRequest *request , NSHTTPURLResponse *response, NSError *error , id JSON ){
NSLog(#"error: %#", error);
}];
[operation start];
this is the example json that I wanted :
"userDevice" : {
"appVersion" : "1.0",
"deviceModel" : "iPhone Simulator",
"productionMode" : false,
"deviceType" : "iPhone Simulator",
"deviceVersion" : "6.1"
}
am I missing something?

AFJSONRequestOperation returns null response in iOS

I am facing 1 problem while using AFJSONRequestOperation. My API Client is as follows
#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
#interface MyAPIClient : AFHTTPClient
+ (MyAPIClient *)sharedAPIClient;
#end
// .m file
#import "MyAPIClient.h"
#implementation MyAPIClient
+ (MyAPIClient *)sharedAPIClient {
static MyAPIClient *sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedClient = [[MyAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kBASE_URL]];
});
return sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:CONTENT_TYPE_FIELD value:CONTENT_TYPE_JSON_VALUE];
self.parameterEncoding = AFJSONParameterEncoding;
return self;
}
#end
Now when I request with following code it returns me "null" response
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:userName,#"email",password,#"password",nil];
NSMutableURLRequest *request = [[MyAPIClient sharedAPIClient] requestWithMethod:#"POST" path:#"login" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
NSDictionary *dictResponse = (NSDictionary*)JSON;
DLog(#"Login Success JSON: %#",JSON);
if (block) {
block(YES,nil);
}
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
DLog(#"Login Error:- %#",error);
if (block) {
block(NO,error);
}
}];
[operation start];
But when I use AFHTTPRequestOperation it reurns me correct output with logged in used info
NSURL *loginUrl = [NSURL URLWithString:kBASE_URL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:loginUrl];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
userName,#"email",password,#"password",nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"login" parameters:params];
//Notice the different method here!
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Raw data Response: %#", responseObject);
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSLog(#"Converted JSON : %#", jsonArray);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"Error: %#", error);
}];
//Enqueue it instead of just starting it.
[httpClient enqueueHTTPRequestOperation:operation];
My server returns JSON response.
What is the problem in above code? Why AFJSONRequestOperation returns null response while
AFHTTPRequestOperation returns me correct response ? Any kind of help is appreciated. Thanks in advance