For my AFNetworking request I expect such "key": "\u0001" response but i am not getting rather I get "key": "". I tried following multiple stack questions but didn't work for me.
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:15];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
manager.securityPolicy.allowInvalidCertificates = true;
manager.securityPolicy.validatesDomainName = false;
[manger.requestSerializer setValue:#"Application/json" forHTTPHeaderField:#"Accept"];
manger.responseSerializer = [AFHTTPResponseSerializer serializer];
[manger GET:url parameters:nil progress:nil success:^(NSURLSessionTask *operation, id responseObject){
NSLog(#"Response REST AP loaded %#", responseObject);
NSMutableDictionary *response = responseObject;
}
It worked in String format when i wrote this line of code
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
But now i don't know how to make it to NSDictionary, i also tried converting this to NSDictionary
NSData *webData = [newStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
This did not work.
Can anyone guide me proper steps how to achieve my expected output.
Thank You
I suggest that you should check responseObject type, for example:
if ([[responseObject class] isSubclassOfClass:[NSDictionary class]]) {
// return responseObject because this is a dictionary
}
else {
NSError *error = nil;
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
NSData *webData = [newStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
return [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
}
NSDictionary* responseDict = [self dataObject:responseData];
use this and then call this method
- (id) dataObject:(NSData*)data
{
return [ NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
Try another ways:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:15];
manager.securityPolicy.allowInvalidCertificates = true;
manager.securityPolicy.validatesDomainName = false;
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:requestURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response REST AP loaded %#", responseObject);
}
Related
I a curl command to get the access token, which looks below command -
curl --data 'client_id=XXX&grant_type=XXX&client_secret=XXX&scope=XXX' "https://abc-internal.XXX.com/as/resourceOwner" -k -i
I need to call this command from my objective C code to get the access token, here is my code which is not working -
NSURL *strURL = [NSURL URLWithString:#"https://abc-internal.XXX.com/as/resourceOwner"];
NSString *icpStr = [strURL absoluteString];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager.requestSerializer setValue:#"XXX" forHTTPHeaderField:#"client_id"];
[manager.requestSerializer setValue:#"XXX" forHTTPHeaderField:#"grant_type"];
[manager.requestSerializer setValue:#"XXX" forHTTPHeaderField:#"client_secret"];
[manager.requestSerializer setValue:#"XXX" forHTTPHeaderField:#"scope"];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
[securityPolicy setValidatesDomainName:NO];
[securityPolicy setAllowInvalidCertificates:YES];
manager.securityPolicy = securityPolicy;
[manager GET:icpStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([responseObject isKindOfClass:[NSData class]])
{
NSError *parseError = nil;
NSDictionary *resultsDictionary = (NSDictionary *) [NSJSONSerialization JSONObjectWithData: responseObject options: 0 error: &parseError];
if (parseError)
{
NSLog(#"Parse Error %#",parseError);
}else{
NSLog(#"Results %#",resultsDictionary);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error %#",error.localizedDescription);
}];
And i get error saying its bad request -
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)"
Any suggestion would be much appreciated. I am new to objective c coding so i would really appreciate if someone can help me here.
NSString *URLString = #"https://abc-internal.XXX.com/as/resourceOwner";
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
manager.responseSerializer =[AFHTTPResponseSerializer serializer];
[manager GET:URLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if ([responseObject isKindOfClass:[NSData class]]) {
NSError *parseError = nil;
NSDictionary *resultsDictionary = (NSDictionary *) [NSJSONSerialization JSONObjectWithData: responseObject options: 0 error: &parseError];
if (parseError)
{
NSLog(#"Parse Error %#",parseError);
}else{
NSLog(#"Results %#",resultsDictionary);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
I'm using AFNetworking to post data into the web. The information I have is the URI which is baseURL/post_user_info and they want input as A JSON object containing each of the name-value pairs. In the code written below I've set the name-value pair in a dictionary. My question is how to make it's json and send it as input value?
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"input_1": #"hello world",
#"input_2": #"my#you.com",
#"input_3": #"newworldorder"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
[manager POST:escapedPath parameters:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
}failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"%#",[error localizedDescription]);
}];
I've updated the code because now I have generated the JSON but if I run the code now it give me Error: 400 which means If input_values is empty, a bad request error will be output.
#interface AFJSONRequestSerializer : AFHTTPRequestSerializer
AFJSONRequestSerializeris a subclass ofAFHTTPRequestSerializerthat encodes parameters as JSON using NSJSONSerialization.
add this AFJSONRequestSerializer is used for send JSON not a Raw Data add this and try once
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
e.g
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
/************** karthik Code added ******************/
AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
/************** karthik Code added ******************/
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
[manager POST:escapedPath parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
NSLog(#"json == %#", json);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"%#", [error localizedDescription]);
}];
Update Params
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
NSMutableDictionary *modify = [NSMutableDictionary new];
[modify setObject:params forKey:#"input_values"];
you get output of
Im using salesforce live agent rest api in ios app, trying to request chat but always fail with 400 request is not a valid ChasitorInit
NSDictionary *parameters =#{ #"SessionId" :self.sessionId,
#"OrganizationId" :ORG_ID,
#"deploymentId" :DEPLOYEMENT_ID,
#"buttonId" :BUTTON_ID,
#"userAgent" :USER_AGENT,
#"language" :LANG,
#"screenResolution" :SCREEN_RES,
#"visitorName" :#"Test Visitor",
#"prechatDetails" :#[],
#"prechatEntities" :#[],
#"receiveQueueUpdates":#"true",
#"isPost" :#"true"
};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = serializer;
[manager.requestSerializer setValue:self.sessionKey forHTTPHeaderField:X_LIVEAGENT_SESSION_KEY];
[manager.requestSerializer setValue:#"null" forHTTPHeaderField:X_LIVEAGENT_AFFINITY];
[manager.requestSerializer setValue:#"1" forHTTPHeaderField:X_LIVEAGENT_SEQUENCE];
[manager.requestSerializer setValue:API_V forHTTPHeaderField:X_LIVEAGENT_API_VERSION];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:ChasitorInit_path parameters:parameters progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
Im using Afnetworking v3 ios8
The request body should be
{
"sessionId": "8f1cfb18-fbd1-4487-90d-e98c0a84e165",
"organizationId": "00D58000000OwMB",
"deploymentId": "57258000000L1mj",
"buttonId": "57358000000L24F",
"userAgent": "",
"language": "en-US",
"screenResolution": "1900x1080",
"visitorName": "Test Visitor",
"prechatDetails": [],
"prechatEntities": [],
"receiveQueueUpdates": true,
"isPost": true
}
What im i doing wrong ? Plz correct me !!
400 Bad request means, you didn't form the request the way server expects.
Check the server logs for whats the issue...
May be it needs data in another form..
and try to check that,you are not passing null value to server..
Try like that:
NSString *Loginurl = [NSString stringWithFormat:#"http://Enter your URL Here"];
NSDictionary *params = #{ #"SessionId" :self.sessionId,
#"OrganizationId" :ORG_ID,
#"deploymentId" :DEPLOYEMENT_ID,
#"buttonId" :BUTTON_ID,
#"userAgent" :USER_AGENT,
#"language" :LANG,
#"screenResolution" :SCREEN_RES,
#"visitorName" :#"Test Visitor",
#"prechatDetails" :#{},
#"prechatEntities" :#{},
#"receiveQueueUpdates":#"true",
#"isPost" :#"true"
};
NSLog(#"Sent parameter to server : %#",params);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/html",nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/plain",nil];
[manager.requestSerializer setValue:self.sessionKey forHTTPHeaderField:X_LIVEAGENT_SESSION_KEY];
[manager.requestSerializer setValue:#"null" forHTTPHeaderField:X_LIVEAGENT_AFFINITY];
[manager.requestSerializer setValue:#"1" forHTTPHeaderField:X_LIVEAGENT_SEQUENCE];
[manager.requestSerializer setValue:API_V forHTTPHeaderField:X_LIVEAGENT_API_VERSION];
AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[policy setValidatesDomainName:NO];
[policy setAllowInvalidCertificates:YES];
[manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"Response from server : %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
_str=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#",_str);
[self getdata:responseObject];
} failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
#pragma mark-DataFromServer
-(void)getdata:(NSDictionary*)RegisterData
{
}
I got the same error in my app. I resolve it by removing request and response Serializer. Only instantiate manager and called post method with parameter.
reqManager = [AFHTTPRequestOperationManager manager];
[reqManager POST:URLString parameters:parameters progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
I'm trying to post data with x-www-form-urlencoded body.
Posting via postman, it is ok
But i cant do it via afnetworking 3. Here is my code
NSDictionary *parameters = #{#"login" : email,
#"password": password};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
self.requestSerializer = [AFJSONRequestSerializer serializer];
NSString *urlString = [NSString stringWithFormat:#"%#/%#", HTTPBaseRequestURL, appendLoginUrl];
NSLog(#"URL %#\njsonString %#", urlString, jsonString);
[self POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFormData:jsonData name:#"data"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
onSuccess(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSString *errorDescription = [NSError serverErrorMessageFromData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]];
NSInteger statusCode = [NSHTTPURLResponse errorCode:(NSHTTPURLResponse*)task.response];
NetworkRequestError *requestError = [[NetworkRequestError alloc] initWithType:
(NSHTTPURLResponse*)task.response ? NetworkRequestErrorTypeServerError : NetworkRequestErrorTypeNoConnection
description:
(NSHTTPURLResponse*)task.response ? errorDescription : nil];
requestError.statusCode = statusCode;
NSLog(#"Error from server: %#, status code = %ld, error type = %lu", requestError.errorDescription, (long)requestError.statusCode, (unsigned long)requestError.type);
onFailure(requestError);
}];
Please, help me to understand how to correctly do this. Thanks!
After commenting I finally found the answer to this. Here's my correctly functioning request now, note the addition of
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
Here's the full code:
NSString *url = [NSString stringWithFormat:#"%#%#",APIBASE,APIUSERENDPOINT];
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
username, #"username",
password, #"password",
nil
];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
try append custom header info ,for example:
[self.requestSerializer setValue:#" application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type];
hope it help for you.
Here . It worked with me . So easy .
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"deviceTokenIOS", #"db487c983ebbe7c2fb066d292bb4318175f54ab27b6b9df7871907e1d0ed62ba",
#"message", #"Hello Dunglt",
nil
];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"db487c983ebbe7c2fb066d292bb4318175f54ab27b6b9df7871907e1d0ed62ba", #"deviceTokenIOS", #"Hello Dunglt", #"message", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:[NSURL URLWithString:url].absoluteString parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];}
I have an UITableViewController and I'm trying getting JSON data from url with this code but I'm getting error.What should I do ?
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://testurl.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": #""};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSData *jsonData = [NSData dataWithContentsOfFile:string];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
[self.customerCards addObject:customer];
}
NSLog(#"GET: %#", string);
NSLog(#"POST: %#", parameters);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
This is the error bloc
2015-03-26 14:27:37.656 SaphiraCrm[13770:3881729] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
I think the problem could be in the fact that you are treating the responseObject as if it was NSData, but according to AFNetworking examples, by default AFHTTPRequestOperationManager's responseSerializer is an AFJSONResponseSerializer, so responseObject is already a parsed JSON represented as an NSDictionary (depends on the serializer).
Therefore, the line
NSString *string = [[NSString alloc] initWithData:responseObject
encoding:NSUTF8StringEncoding];
returns nil, which causes the next line
NSData *jsonData = [NSData dataWithContentsOfFile:string];
to raise the exception.
I would suggest that you check responseObject is what you expect it to be and refactor your code accordingly.
...
[manager POST:urlPath
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
NSLog(#"Response is a %# and contains: %#", [responseObject class], responseObject);
// Process responseObject according to its type
...
Note:
It is very likely that the above is just the consequence of a previous mistake in the way you set your seriliazer's configuration, since you set first the acceptableContentType first and then overwrite it with the default one.
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
...
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// this is likely to invalidate the previous, since you overwritting
// the manager's serializer with a new one with default configuration.
Okey I figured Out how can I do this.
There is my code
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": #""};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
NSLog(#"%#",customersArray);
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
[self.customerCards addObject:customer];
}
[self.tableView reloadData];
NSLog(#"GET: %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];