我正在使用NSURLConnection
将相同的数据 ( NSString
) 发送到服务器,并且我想与它们一起添加图像或文件,那么内容类型的值是什么?
编码
- (NSData *)encodingData:(NSMutableDictionary *)dictionary
{
NSMutableArray *arrayPosts = [[NSMutableArray alloc] init];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *encodedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodedValue = [obj stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[arrayPosts addObject:[NSString stringWithFormat:@"%@=%@",encodedKey,encodedValue]];
}];
NSString *encodedArrayPosts = [arrayPosts componentsJoinedByString:@"&"];
return [encodedArrayPosts dataUsingEncoding:NSUTF8StringEncoding];
}
发送数据
- (void)startAsyncRequest
{
// Enable the network activity indicator in the status bar
[self enableActivityIndicatorInStatusBar];
// Setting of the request
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
[urlRequest setHTTPMethod:self.method];
[urlRequest setHTTPBody:[self encodingData:self.dictionaryPosts]];
// Send the request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (connection) {
// Connection succeded
self.receiveData = [NSMutableData data];
} else {
// Connection Failed
self.error = @"Connection Failed";
// Inform the user that the connection failed
[self.delegate requestFailed:self];
}
}