我一直在尝试在我的iPhone应用程序中创建参数的NSDictionary,并希望将它(通过POST HTTP请求,请求中还有一些其他参数)发送到rails服务器上的ruby以供使用通过一个以哈希表作为参数的ruby方法。
答案 0 :(得分:5)
是的,您需要明确编码参数。
这是相对简单的。这是我使用的NSMutableURLRequest的扩展,它将字符串字典编码为POST参数。
@interface NSMutableURLRequest (WebServiceClient)
+ (NSString *) encodeFormPostParameters: (NSDictionary *) parameters;
- (void) setFormPostParameters: (NSDictionary *) parameters;
@end
@implementation NSMutableURLRequest (WebServiceClient)
+ (NSString *) encodeFormPostParameters: (NSDictionary *) parameters {
NSMutableString *formPostParams = [[[NSMutableString alloc] init] autorelease];
NSEnumerator *keys = [parameters keyEnumerator];
NSString *name = [keys nextObject];
while (nil != name) {
NSString *encodedValue = [((NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef) [parameters objectForKey: name], NULL, CFSTR("=/:"), kCFStringEncodingUTF8)) autorelease];
[formPostParams appendString: name];
[formPostParams appendString: @"="];
[formPostParams appendString: encodedValue];
name = [keys nextObject];
if (nil != name) {
[formPostParams appendString: @"&"];
}
}
return formPostParams;
}
- (void) setFormPostParameters: (NSDictionary *) parameters {
NSString *formPostParams = [NSMutableURLRequest encodeFormPostParameters: parameters];
[self setHTTPBody: [formPostParams dataUsingEncoding: NSUTF8StringEncoding]];
[self setValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField: @"Content-Type"];
}
@end