我正在为 iOS 创建一个应用程序,并且正在使用这个OAuth 库。GET 请求似乎工作正常,但一旦我尝试发出 POST 请求,我就会收到以下错误:
[代码 32] 无法验证您的身份。
现在我不太确定发生了什么,因为 POST 请求的生成与 GET 请求非常相似。任何想法是什么导致了这个错误?
这是生成请求的代码:
+ (NSURLRequest *)preparedRequestForPath:(NSString *)path
parameters:(NSDictionary *)queryParameters
HTTPmethod:(NSString *)HTTPmethod
oauthToken:(NSString *)oauth_token
oauthSecret:(NSString *)oauth_token_secret
{
if (!HTTPmethod
|| !oauth_token) return nil;
NSMutableDictionary *allParameters = [self standardOauthParameters];
allParameters[@"oauth_token"] = oauth_token;
if (queryParameters) [allParameters addEntriesFromDictionary:queryParameters];
NSString *parametersString = CHQueryStringFromParametersWithEncoding(allParameters, NSUTF8StringEncoding);
NSString *request_url = API_URL;
if (path) request_url = [request_url stringByAppendingString:path];
NSString *oauth_consumer_secret = CONSUMER_SECRET;
NSString *baseString = [HTTPmethod stringByAppendingFormat:@"&%@&%@", request_url.utf8AndURLEncode, parametersString.utf8AndURLEncode];
NSString *secretString = [oauth_consumer_secret.utf8AndURLEncode stringByAppendingFormat:@"&%@", oauth_token_secret.utf8AndURLEncode];
NSString *oauth_signature = [self.class signClearText:baseString withSecret:secretString];
allParameters[@"oauth_signature"] = oauth_signature;
NSString *queryString;
if (queryParameters) queryString = CHQueryStringFromParametersWithEncoding(queryParameters, NSUTF8StringEncoding);
if (queryString) request_url = [request_url stringByAppendingFormat:@"?%@", queryString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:request_url]];
request.HTTPMethod = HTTPmethod;
NSMutableArray *parameterPairs = [NSMutableArray array];
[allParameters removeObjectsForKeys:queryParameters.allKeys];
for (NSString *name in allParameters) {
NSString *aPair = [name stringByAppendingFormat:@"=\"%@\"", [allParameters[name] utf8AndURLEncode]];
[parameterPairs addObject:aPair];
}
NSString *oAuthHeader = [@"OAuth " stringByAppendingFormat:@"%@", [parameterPairs componentsJoinedByString:@", "]];
[request setValue:oAuthHeader forHTTPHeaderField:@"Authorization"];
if ([HTTPmethod isEqualToString:@"POST"]
&& queryParameters != nil) {
NSData *body = [queryString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:body];
}
return request;
}
编辑
我设置 HTTP 正文的代码的最后几行似乎导致了问题。当我删除线条时
NSData *body = [queryString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:body];
一切正常,除非参数特别大,比如发送 base64 编码的图像,但显然失败了……我能做些什么来解决这个问题?