0

我希望将 NSDictionary 发送到运行 Django 的服务器上,如果我不得不做很少或根本不需要编写编码器/解析器的工作,我会更愿意。

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

4

2 回答 2

1

iOS 5 在框架中支持它。看看 NSJSONSerialization。这是帖子的示例代码。下面的代码中省略了请求对象的创建。

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]];
于 2014-05-19T14:14:10.310 回答
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];

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

于 2012-05-25T19:03:40.547 回答