J'essaie de faire une demande POST qui a des champs HTTPHeader et un corps HTTP à l'API youtube.
Auparavant, dans la version 2.0 de AFNetworking, je le faisais de cette façon, ce qui fonctionnait bien:
NSDictionary *parameters = @{@"snippet": @{@"textOriginal":self.commentToPost.text,@"parentId":self.commentReplyingTo.commentId}};
NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/comments?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval=[[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"Reply JSON: %@", responseObject);
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);
}];
[operation start];
Les documents de migration pour la version 3.0 remplacent AFHTTPRequestOperationManager
par AFHTTPSessionManager
Cependant, je n'arrive pas à trouver une méthode HTTPRequestOperationWithRequest
pour la AFHTTPSessionManager
.
J'ai essayé d'utiliser la variable constructingBodyWithBlock
mais cela ne fonctionne peut-être pas car je ne le fais pas correctement.
C'est ce que j'ai jusqu'à présent qui ne fonctionne pas:
NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
serializer.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager POST:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithHeaders:nil body:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"Reply JSON: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);
}];
J'ai été capable de comprendre cela moi-même.
Voici la solution.
Vous devez d’abord créer la variable NSMutableURLRequest
à partir de AFJSONRequestSerializer
, dans laquelle vous pouvez définir le type de méthode sur POST.
Sur cette demande, vous obtenez setHTTPBody
après avoir défini votre HTTPHeaderFields
. Assurez-vous de définir le corps après avoir défini les champs d'en-tête pour le type de contenu, sinon l'API générera une erreur 400.
Ensuite, sur le gestionnaire, créez une dataTaskWithRequest
en utilisant la NSMutableURLRequest
ci-dessus. N'oubliez pas de resume
la dataTask à la fin, sinon rien ne sera envoyé pour le moment. Voici le code de ma solution. J'espère que quelqu'un l'utilisera avec succès:
NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"Reply JSON: %@", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(@"Error: %@, %@, %@", error, response, responseObject);
}
}] resume];
Une autre manière d’appeler une méthode POST avec AFNetworking 3.0 est la suivante:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"success!");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error: %@", error);
}];
J'espère que ça aide!
-(void)postRequest:(NSString *)urlStr parameters:(NSDictionary *)parametersDictionary completionHandler:(void (^)(NSString*, NSDictionary*))completionBlock{
NSURL *URL = [NSURL URLWithString:urlStr];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:URL.absoluteString parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
completionBlock(@"Success",json);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: %@", error);
completionBlock(@"Error",nil);
}];
}
Cette méthode fonctionne bien pour AFNetworking 3.0.
Pour HTTPBody
avec JSON
[sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[sessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError * __autoreleasing * error) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:error];
NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return argString;
}];
[sessionManager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if (completion) {
completion(responseObject, nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (completion) {
NSData *errorData = [error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"];
NSDictionary *responseErrorObject = [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
completion(responseErrorObject, error);
}
}];
Pour HTTPBody
avec format de chaîne personnalisé
[sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[sessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError * __autoreleasing * error) {
NSString *argString = [self dictionaryToString:parameters];
return argString;
}];
[sessionManager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if (completion) {
completion(responseObject, nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (completion) {
NSData *errorData = [error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"];
NSDictionary *responseErrorObject = [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
completion(responseErrorObject, error);
}
}];
La réponse acceptée de #Pranoy C est convertie pour AFNetworking 3.0
NSError *writeError = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120];
[request setHTTPMethod:@"POST"];
[request setValue: @"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue: @"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"Reply JSON: %@", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(@"Error: %@", error);
NSLog(@"Response: %@",response);
NSLog(@"Response Object: %@",responseObject);
}
}] resume];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:log.text, @"email", pass.text, @"password", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:@"add your webservice URL here" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"%@", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
/**
* Services gateway
* Method get response from server
* @parameter -> object: request josn object ,apiName: api endpoint
* @returm -> void
* @compilationHandler -> success: status of api, response: respose from server, error: error handling
*/
+ (void)getDataWithObject:(NSDictionary *)object onAPI:(NSString *)apiName withController:(UIViewController*)controller
:(void(^)(BOOL success,id response,NSError *error))compilationHandler {
controller = controller;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// set request type to json
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// post request to server
[manager POST:apiName parameters:object success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject
options:0
error:&error];
//NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
////
// check the status of API
NSDictionary *dict = responseObject;
NSString *statusOfApi = [[NSString alloc]initWithFormat:@"%@"
,[dict objectForKey:@"OK"]];
// IF Status is OK -> 1 so complete the handler
if ([statusOfApi isEqualToString:@"1"] ) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
compilationHandler(TRUE,responseObject,nil);
} else {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *errorMessages = [responseObject objectForKey:@"messages"];
NSString *message = [errorMessages objectAtIndex:0];
[Utilities showAlertViewWithTitle:apiName message:message];
compilationHandler(FALSE,responseObject,nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *message = [NSString stringWithFormat:@"%@",[error localizedDescription]];
NSLog(@"Message is %@", message);
NSString *errorMessage = [NSString stringWithFormat:@"%@",[error localizedDescription]];
if (!([message rangeOfString:@"The request timed out."].location == NSNotFound)) {
[Utilities showAlertViewWithTitle:apiName message:errorMessage];
}
compilationHandler(FALSE,errorMessage,nil);
}];
}