有没有快速的方法将NSDictionary发布到Python / Django服务器?

时间:2012-05-25 18:02:50

标签: django ios5

我正在寻找将NSDictionary发送到运行Django的服务器,如果我不得不做很少或根本没有编写编码器/解析器的工作。

有没有简单的方法来完成这项任务?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

然后它就像:

一样简单
NSURL *url = [NSURL URLWithString:@"http://posttestserver.com/post.php"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithInt:42], @"number",
    @"apple", @"brand", nil];
NSURLRequest *request = [NSURLRequest postRequestWithURL:url parameters:params];
[NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:nil];

请注意,在此示例中,我们并不关心响应。如果您关心它,请提供一个块,以便您可以使用它。