This question already has answers here:
afnetworking 3.0 Migration: how to POST with headers and HTTP Body
(10 answers)
Closed 5 years ago.
I am working on a project that using AFNetworking to connect with API interface. My problem is that how to send a request to the backend with body content that includes email, deviceId. I have found many solutions that all compatible with AFNetworking 2.0 not 3.0.
Now I am using SessionManager, when i initialize request, how can I add content body context?
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
NSString *stringData = [[NSString alloc]initWithData:jsonData encoding:NSASCIIStringEncoding];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
[manager POST:_urlString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSString *link = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#",link);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I have tried to put email& deviceId into [manager POST parameter: Dict], but it is not working.
Can someone tell me how to add body to AFNetworking 3.0? Thanks
if i got your question correctly it shouldnt be that hard. its similar to the 2.0 version as well.
NSDictionary *parameters = #{#"username": _username.text,
#"deviceId": deviceIdString,
};
NSMutableDictionary * parameters = [[NSMutableDictionary alloc]initWithDictionary:params];
NSURL *baseURL = [NSURL URLWithString:#"http://url.com/ws/test.php"];
AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
//Response
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(error.code==-1001){
//Handle the error
}
}];
Related
I use the following code to make a GET request including a header Authorization but does not seem to work...the get request does not include the authorization token. Any ideas?
// 1 - define resource URL
NSURL *URL = [NSURL URLWithString:#"https://myurl"];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#",Token] forHTTPHeaderField:#"Authorization"];
manager.requestSerializer = requestSerializer;
//3 - set a body
NSDictionary *body =#{#"email":#"a#gmail.com"};
//4 - create request
[manager GET:URL.absoluteString
parameters:body
progress:nil
//5 - response handling
success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
NSLog(#"Reply POST JSON: %#", responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error on machine token: %#", error);
}
];
There are other questions with similar titles but none of them helped me. I've to send a PUT request to server in order to change the status of appointment so I've made this method -(void)appointmentStatusChangedTo:(NSString *)statusID atAppointmentID:(NSString *)appointmentID In which I'm setting the URL and Parameters as
NSString *string = [NSString stringWithFormat:#"%#/API/Appointments/3",BaseURLString];
NSDictionary *para = #{
#"AppointmentStatusId":statusID,
#"ID":appointmentID
};
Then I've made URL request as
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"PUT" URLString:string parameters:para error:nil];
After that I'm setting the header for an authorization token as
NSString *token = [NSString stringWithFormat:#"Bearer %#",[[NSUserDefaults standardUserDefaults] objectForKey:#"userToken"]];
[req setValue:token forHTTPHeaderField:#"Authorization"];
So finally I'm calling it as
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error){
if (!error) {
if (response) {
NSLog(#"Respose Object: %#",responseObject);
[self.patientsAppointmentsTableView reloadData];
}
}
else {
// NSLog(#"Error: %#, %#, %#", error, response, responseObject);
NSLog(#"Error: %#", error.localizedDescription);
}
}] resume];
Now it is successfully sending the data to the server but as a response I'm getting
Error: The data couldn’t be read because it isn’t in the correct
format.
I am not sure what the response might look like at the moment as I'm not in contact with backend guy. But as far as I remember it was just a simple 1. SO kindly tell me how to handle any type of response using AFNetworking 3.0 or any change in my code.
try to use below code:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
manager.requestSerializer=serializer;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Try following code using Afnetworking 3.0
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#",responseObject);
self.responseHandlers(YES,responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
self.responseHandlers(NO,nil);
}];
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
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 am getting a 404 error while posting with JSON parameters at the https://api.hackerearth.com/codemonk/v1/topicdetail/. The server uses POST HTTP method to get a topic's details & JSON response is expected when successful. The POST parameter is id of the topic object. POST Parameters are expected to be in JSON.
I am using AFNetworking as follows -
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *params = [NSDictionary dictionaryWithObject:#1 forKey:#"id"];
NSString *str = #"https://api.hackerearth.com/codemonk/v1/topic-detail/";
NSString *encodedStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[manager POST:encodedStr
parameters:params
success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(#"responseObject : %#",responseObject);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(#"error : %#", error.localizedDescription);
}];
This is regular stuff but don't know why I can't seem to get it correct now. I am only getting a 404 Page Not Found error. This is not a server side issue for sure. Any help guys ?
Maybe this will help.
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
operationManagerInstance.requestSerializer = requestSerializer;
=============UPDATE
I have 404 when copying your URL. It's because hyphen symbol between topic-detail is not actually hyphen. It's some special character that doesn't work.
https://api.hackerearth.com/codemonk/v1/topic-detail/
Instead I deleted it and typed hyphen manually and it works fine.
Remove the following line
NSString *encodedStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Try the following:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *params = [NSDictionary dictionaryWithObject:#1 forKey:#"id"];
NSString *str = #"https://api.hackerearth.com/codemonk/v1/topic-detail/";
[manager POST:str
parameters:params
success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(#"responseObject : %#",responseObject);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(#"error : %#", error.localizedDescription);
}];