我为我的应用程序使用 Flickr API 来管理用户的照片。我决定使用 Apple 的类进行身份验证,它对我来说效果很好。现在我的应用程序已经过身份验证,并拥有所有必要的令牌和密钥,因此可以通过 flickr.photos.search、flickr.test.login 等方法的身份验证执行 GET 请求。但我花了几天时间尝试使用http://api.flickr.com/services/upload/ 和他们的说明来执行上传。他们说请求应该有参数“照片”,并且这个参数不应该包含在签名中。这很清楚,但我不知道如何在请求中实现这个参数。
#import "FlickrUploader.h"
#import "HMACSH1.h"
#import "Prefs.h"
#import "NSString+URLEncode.h"
@implementation FlickrUploader
- (void)uploadPhotoAtPath:(NSString*)filePath {
NSString *upload_api_url = @"http://api.flickr.com/services/upload/";
NSString *oauth_nonce = [NSString stringWithFormat:@"%d", 10000000 + arc4random()%1000000];
NSString *oauth_timestamp = [NSString stringWithFormat:@"%d", (long)[[NSDate date] timeIntervalSince1970]];
NSString *oauth_consumer_key = CONSUMER_KEY;
NSString *oauth_signature_method = @"HMAC-SHA1";
NSString *oauth_version = @"1.0";
NSString *oauth_token = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_ACCESS_TOKEN_KEY];
//creating basestring to make signature without a 'photo' argument according to API
NSMutableString *basestring = [[NSMutableString alloc] initWithCapacity:8];
[basestring appendFormat:@"&oauth_consumer_key=%@",oauth_consumer_key];
[basestring appendFormat:@"&oauth_nonce=%@",oauth_nonce];
[basestring appendFormat:@"&oauth_signature_method=%@",oauth_signature_method];
[basestring appendFormat:@"&oauth_timestamp=%@",oauth_timestamp];
[basestring appendFormat:@"&oauth_token=%@", oauth_token];
[basestring appendFormat:@"&oauth_version=%@",oauth_version];
//this is may class to make HMAC-SHA1 signature (it works for authentication and for GET requests)
HMACSH1 *hMACSH1 = [[HMACSH1 alloc] init];
NSMutableString *urlEncodedBaseString = [[NSMutableString alloc] initWithCapacity:3];
[urlEncodedBaseString appendString:@"POST"];
[urlEncodedBaseString appendFormat:@"&%@",[upload_api_url urlEncodedString]];
[urlEncodedBaseString appendFormat:@"&%@",[basestring urlEncodedString]];
NSString *oauth_token_secret = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_TOKEN_SECRET_KEY];
NSString *hash_key = [CONSUMER_SECRET stringByAppendingFormat:@"&%@",oauth_token_secret];
NSString *oauth_signature = [hMACSH1 hmacSH1base64ForData:urlEncodedBaseString keyValue:hash_key];
//creating url for request
NSMutableString *urlString = [[NSMutableString alloc] initWithCapacity:8];
[urlString appendFormat:@"%@",upload_api_url];
[urlString appendFormat:@"?"];
[urlString appendString:basestring];
[urlString appendFormat:@"&oauth_signature=%@", oauth_signature];
NSURL *authURL = [[NSURL alloc] initWithString:urlString];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:authURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
request.HTTPMethod = @"POST";
UIImage *img = [UIImage imageNamed:filePath];
NSData *imgData = UIImageJPEGRepresentation(img, 0.8);
//here I don't know what to do :((( perhaps NSOutputStream
}