【发布时间】:2011-10-05 13:45:33
【问题描述】:
我正在使用 Jon Crosby (google code link) 的 OAuthConsumer 库
我已经成功地使用访问和请求令牌/秘密设置了我的项目,以便向服务器 (GET) 发出基本的授权 http 请求。但是现在我需要创建一个将图像上传到服务器的调用......(POST)
据我所知,我需要自己定义整个 httpBody(如果我错了,请纠正我)。我在某处发现了一些将数据附加到 httpBody 的示例代码,但我完全不知道我在做什么。我是这样做的:
// create url request
urlRequest = [[[OAMutableURLRequest alloc] initWithURL:urlToServerGoesHere
consumer:authentication.consumer
token:authentication.token
realm:nil
signatureProvider:nil] autorelease];
// apply http method on request
[urlRequest setHTTPMethod:@"POST"];
// define boundary and content-type of file in header of request
NSString* boundary = @"----IMAGE_UPLOAD";
NSString* contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[urlRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
// Create entire body
NSMutableData* body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"image\"; filename=\"upload.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:body];
在上面代码末尾应用httpBody时,OAMutableRequest内部会抛出异常。我在想我做错了什么或没有设置。它似乎与我没有使用的参数数组有关......?
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]' *** Call stack at first throw:(0 CoreFoundation 0x00ddc5a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f30313 objc_exception_throw + 44
2 CoreFoundation 0x00dd21cc -[__NSArrayI objectAtIndex:] + 236
3 TwooWrapper 0x0000d310 -[OAMutableURLRequest parameters] + 610
4 TwooWrapper 0x0000d45d -[OAMutableURLRequest _signatureBaseString] + 39
5 TwooWrapper 0x0000c619 -[OAMutableURLRequest prepare] + 213
6 TwooWrapper 0x0000c17c -[OADataFetcher
有没有人知道如何通过 Oauth 使用我正在使用的这个库上传文件,或者有什么建议?会有很大帮助!谢谢
【问题讨论】:
标签: objective-c ios nsurlrequest