如何使用2个参数进行POST NSURLRequest?

时间:2014-09-06 14:49:02

标签: ios objective-c post nsurlrequest

我想向NSURLRequest添加2个参数。 有没有办法或者我应该使用AFnetworking?

2 个答案:

答案 0 :(得分:32)

如果您使用AFNetworking,可能会更容易。如果您有自己想做的事情,可以使用NSURLSession,但必须编写更多代码。

  1. 如果您使用AFNetworking,它会处理序列化请求,区分成功和错误等所有这些细节:

    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);
    }];
    

    这假定服务器的响应是JSON。如果不是(例如,如果是纯文本或HTML),则可以在POST之前加上:

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
  2. 如果使用NSURLSession自行完成,您可以像这样构建请求:

    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]];
    

    您现在可以使用NSURLSession发起请求。例如,您可以这样做:

    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];
    

    其中

    /** 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];
    }
    

    /** 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];
    }
    

答案 1 :(得分:1)

NSDictionary *params = @{@"firstname": @"John", @"lastname": @"Doe"};
NSMutableString *str = [NSMutableString stringWithString:@"http://yoururl.com/postname?"];
NSArray *keys = [params allKeys];
NSInteger counter = 0;
for (NSString *key in keys) {
    [str appendString:key];
    [str appendString:@"="];
    [str appendString:params[key]];
    if (++counter < keys.count) { // more params to come...
        [str appendString:@"&"];
    }
}
NSURL *url = [NSURL URLWithString:str];
// should give you: http://yoururl.com/postname?firstname=John&lastname=Doe
// not tested, though