有没有一种快速的方法将NSDictionary发布到Python/Django服务器?
我希望向运行Django的服务器发送一个NSDictionary,如果我只需要很少或根本不需要编写编码器/解析器,我会更愿意这样做有没有一种快速的方法将NSDictionary发布到Python/Django服务器?,django,ios5,Django,Ios5,我希望向运行Django的服务器发送一个NSDictionary,如果我只需要很少或根本不需要编写编码器/解析器,我会更愿意这样做 是否有一种简单的方法来完成此任务?iOS不支持将此作为一行程序来完成,但您可以这样做: @interface NSString (URLEncoding) - (NSString *)urlEncodedUTF8String; @end @interface NSURLRequest (DictionaryPost) + (NSURLRequest *)po
是否有一种简单的方法来完成此任务?iOS不支持将此作为一行程序来完成,但您可以这样做:
@interface NSString (URLEncoding)
- (NSString *)urlEncodedUTF8String;
@end
@interface NSURLRequest (DictionaryPost)
+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
parameters:(NSDictionary *)parameters;
@end
@implementation NSString (URLEncoding)
- (NSString *)urlEncodedUTF8String {
return (id)CFURLCreateStringByAddingPercentEscapes(0, (CFStringRef)self, 0,
(CFStringRef)@";/?:@&=$+{}<>,", kCFStringEncodingUTF8);
}
@end
@implementation NSURLRequest (DictionaryPost)
+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
parameters:(NSDictionary *)parameters {
NSMutableString *body = [NSMutableString string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
for (NSString *key in parameters) {
NSString *val = [parameters objectForKey:key];
if ([body length])
[body appendString:@"&"];
[body appendFormat:@"%@=%@", [[key description] urlEncodedUTF8String],
[[val description] urlEncodedUTF8String]];
}
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
return request;
}
@end
请注意,在本例中,我们并不关心响应。如果您关心它,请提供一个块,这样您就可以使用它做一些事情。iOS 5在框架中支持它。看看NSJSONSerialization。下面是post的示例代码。下面的代码中省略了创建请求对象
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObjectsAndKeys:API_KEY, @"apiKey", userName, @"loginUserName", hashPassword, @"hashPassword", nil], @"loginReq", nil];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
NSError *error = nil;
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error]];
这是否支持复杂对象?包含和字典数组的字典?您现在可以使用NSString的“stringByRemovingPercentEncoding”方法,而不是此答案中的NSString类别增强。(iOS 7.0+)
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObjectsAndKeys:API_KEY, @"apiKey", userName, @"loginUserName", hashPassword, @"hashPassword", nil], @"loginReq", nil];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
NSError *error = nil;
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error]];