如何使用 2 个参数制作 POST NSURLRequest? [英] How to make POST NSURLRequest with 2 parameters?
问题描述
我想向 NSURLRequest
添加 2 个参数.有没有办法或者我应该使用 AFnetworking?
I want to add 2 parameters to NSURLRequest
.
Is there a way or should I use AFnetworking?
推荐答案
如果您使用 AFNetworking,这可能会更容易.如果你有一些自己的愿望,你可以使用NSURLSession
,但你必须编写更多的代码.
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.
如果您使用 AFNetworking,它会处理序列化请求、区分成功和错误等所有这些血腥的细节:
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);
}];
这里假设来自服务器的响应是 JSON.如果不是(例如,如果是纯文本或 HTML),您可以在 POST
之前加上:
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];
如果自己用 NSURLSession
来做,你可以像这样构造请求:
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]];
您现在可以使用 NSURLSession
发起请求.例如,您可能会这样做:
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];
哪里
/** 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];
}
这篇关于如何使用 2 个参数制作 POST NSURLRequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!