2017-02-15 5 views
1

Je crée un code de services Web de démonstration sans utiliser AFNetworking Framework. Mes HTTPRequest Paramètre dans Dictionary. Comment puis-je le définir sur HTTPBody?Comment ajouter un dictionnaire en tant que paramètre de requête pour HTTPBody dans NSJSONSerialization?

mon code est le suivant

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl]; 

[request setHTTPMethod:@"POST"]; 

NSString *postString = "Request Parameter"; 

[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 
// NSLog(@"requestReply: %@", requestReply); 

    NSError *jsonError; 
    NSData *objectData = [requestReply dataUsingEncoding:NSUTF8StringEncoding]; 
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData 
                 options:NSJSONReadingMutableContainers 
                  error:&jsonError]; 
    NSLog(@"requestReply: %@", json); 

}] resume]; 
+0

avez-vous des en-têtes dans la requête pourriez-vous avoir la possibilité d'oublier de l'ajouter? –

+0

comme 'Content-Type' ou' Accept'? –

+0

chekc une fois dans le développeur backend quels sont les autres paramètres doivent ajouter –

Répondre

0

Got Les données

NSURL *stringwithUrl = [NSURL URLWithString:@"XXXX"]; 
    NSMutableURLRequest *requestUrl = [NSMutableURLRequest requestWithURL:stringwithUrl]; 
    [requestUrl setHTTPMethod:@"POST"]; 

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"Value==",@"Key", nil]; 
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil]; 

    NSString *mainString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; 

    NSString *requestString = @"request="; 

    NSString *finalString = [requestString stringByAppendingString:mainString]; 

    [requestUrl setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding]]; 

    NSURLSession *sesion = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

    [[sesion dataTaskWithRequest:requestUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 

     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 

     NSLog(@"%@",dict); 

    }]resume]; 
0

Vérifiez votre état avec mon code de travail,

NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL] 
                 cachePolicy:NSURLRequestUseProtocolCachePolicy 
                timeoutInterval:50.0]; 
[_request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; // Interact your backend developer for header 
[_request addValue:@"application/json" forHTTPHeaderField:@"Accept"];// Interact your backend developer for header 

[_request setHTTPMethod:@"POST"]; 

NSError *error; 
NSData *_inputData = [NSJSONSerialization dataWithJSONObject:inputDictionary options:0 error:&error]; 
[_request setHTTPBody:_inputData]; 

NSURLSessionDataTask *_fetchData = [[[self class] session] dataTaskWithRequest:_request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    if(!error) { 
     NSError* error; 
     completionBlock(data,error,1); 
    } else { 
     completionBlock(data,error,0); 
    } 
}]; 
[_fetchData resume]; 
1

Vous pouvez faire comme ça avec AFnetworking et sans Af Networking.

NSString *stringUrl = @"xxx"; 

    NSURLSessionConfiguration *myConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; 

    AFHTTPSessionManager *myManager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:myConfiguration]; 
    AFHTTPResponseSerializer *mySerilizer = [[AFHTTPResponseSerializer alloc]init]; 
    [myManager setResponseSerializer:mySerilizer]; 

    NSDictionary *param = [[NSDictionary alloc]initWithObjectsAndKeys:@"value==",@"Token", nil]; 

    NSData *data = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil]; 

    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; 

    NSDictionary *requestParameter = [NSDictionary dictionaryWithObject:string forKey:@"request"]; 

    [manager POST:stringUrl parameters:requestParameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 

     NSError *error; 
     if(!error) 
     { 

      NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error]; 
      NSLog(@"%@",dict); 

     } 
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 

    }]; 

Sans Dictionnaire

NSString *urlString = @"xxxx"; 

    // Do any additional setup after loading the view, typically from a nib. 
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:configuration]; 
    AFHTTPResponseSerializer *serilizer = [[AFHTTPResponseSerializer alloc]init]; 
    [manager setResponseSerializer:serilizer]; 

    NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"value",@"key", nil]; 
    [manager POST:urlString parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 

     NSError *error; 
     if(!error) 
     { 
      NSDictionary *finalData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error]; 
      NSLog(@"Final Data is %@",finalData); 

     } 

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 

}]; 

Sans AFNetworking

NSString *MyUrlString = @"xxxx"; 
    NSURL *url = [NSURL URLWithString:MyUrlString]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    [request setHTTPMethod:@"POST"]; 
    NSString *postString = @"key=value"; 
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
     NSError *jsonError; 
     NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data 
                  options:NSJSONReadingMutableContainers 
                  error:&jsonError]; 
     NSLog(@"requestReply: %@", json); 

    }] resume]; 

Note: -Ne pas oublier de mettre CV

Merci