我有以下方法用于创建一个NSMutableURLRequest
包含在NSMutableDictionary
.
+ (NSMutableURLRequest *)createURLRequestWithURL:(NSString *)URL andPostData:(NSMutableDictionary *)postDictionary {
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]init];
NSString *postString = @"";
NSString *postLength = nil;
NSData *postData = nil;
//convert post distionary into a string
if (postDictionary) {
for (NSString *key in postDictionary) {
if ([postString length] != 0) {
postString = [postString stringByAppendingString:@"&"];
}
postString = [postString stringByAppendingFormat:@"%@=%@", [self urlEncodeString:key], [self urlEncodeString:[postDictionary valueForKey:key]]];
}
}
//get length of post and convert post into a data object
postLength = [NSString stringWithFormat:@"%d", [postString length]];
postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//setup the request
[urlRequest setURL:[NSURL URLWithString:URL]];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:postData];
return urlRequest;
}
到目前为止,我一直只使用字符串数据作为postDictionary
.
我的问题是我应该如何修改此代码以发送其他类型的值?具体来说,我正在尝试将图像发送到服务器。