Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

ios - How to make POST NSURLRequest with 2 parameters?

I want to add 2 parameters to NSURLRequest. Is there a way or should I use AFnetworking?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It will probably be easier to do if you use AFNetworking. If you have some desire to do it yourself, you can use NSURLSession, but you have to write more code.

  1. If you use AFNetworking, it takes care of all of this gory details of serializing the request, differentiating between success and errors, etc.:

    NSDictionary *params = @{@"firstname": @"John", @"lastname": @"Doe"};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:urlString parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"responseObject = %@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error = %@", error);
    }];
    

    This assumes that the response from the server is JSON. If not (e.g. if plain text or HTML), you might precede the POST with:

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
  2. If doing it yourself with NSURLSession, you might construct the request like so:

    NSDictionary *params = @{@"firstname": @"John", @"lastname": @"Doe"};
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[self httpBodyForParameters:params]];
    

    You now can initiate the request with NSURLSession. For example, you might do:

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"dataTaskWithRequest error: %@", error);
        }
    
        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
            if (statusCode != 200) {
                NSLog(@"Expected responseCode == 200; received %ld", (long)statusCode);
            }
        }
    
        // If response was JSON (hopefully you designed web service that returns JSON!),
        // you might parse it like so:
        //
        // NSError *parseError;
        // id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
        // if (!responseObject) {
        //     NSLog(@"JSON parse error: %@", parseError);
        // } else {
        //     NSLog(@"responseObject = %@", responseObject);
        // }
    
        // if response was text/html, you might convert it to a string like so:
        //
        // NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        // NSLog(@"responseString = %@", responseString);
    }];
    [task resume];
    

    Where

    /** Build the body of a `application/x-www-form-urlencoded` request from a dictionary of keys and string values
    
     @param parameters The dictionary of parameters.
     @return The `application/x-www-form-urlencoded` body of the form `key1=value1&key2=value2`
     */
    - (NSData *)httpBodyForParameters:(NSDictionary *)parameters {
        NSMutableArray *parameterArray = [NSMutableArray array];
    
        [parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
            NSString *param = [NSString stringWithFormat:@"%@=%@", [self percentEscapeString:key], [self percentEscapeString:obj]];
            [parameterArray addObject:param];
        }];
    
        NSString *string = [parameterArray componentsJoinedByString:@"&"];
    
        return [string dataUsingEncoding:NSUTF8StringEncoding];
    }
    

    and

    /** Percent escapes values to be added to a URL query as specified in RFC 3986.
    
     See http://www.ietf.org/rfc/rfc3986.txt
    
     @param string The string to be escaped.
     @return The escaped string.
     */
    - (NSString *)percentEscapeString:(NSString *)string {
        NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"];
        return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...