2013-01-31 20 views
5

Tôi đang cố gắng tích hợp "tumblr" vào ứng dụng của mình. Tôi có thể nhận được mã thông báo truy cập thành công. Tuy nhiên, khi tôi cố gắng để viết, tôi nhận được lỗi sauKhông thể đăng trên tumblr từ iOS OAuth1.0, ứng dụng khách OAConsumer

{"meta":{"status":401,"msg":"Not Authorized"},"response":[]} 

Tôi đang sử dụng client OAuthConsumer dành cho iOS, mà tôi đã kéo nếu từ MGTwitterEngine.

Đây là những gì tôi đã thử.

#import "ViewController.h" 


#define consumer_key @"u9iZvT8KIlrTtUrh3vUeXXXXXXXXXXXXXAfgpThGyom8Y6MKKCnU" 
#define consumer_secret @"xfA10mQKmALlpsnrFXXXXXXXXXXXXXXXXXXXXXXXXXX" 
#define request_token_url @"http://www.tumblr.com/oauth/request_token" 
#define access_token_url @"http://www.tumblr.com/oauth/access_token" 
#define authorize_url @"http://www.tumblr.com/oauth/authorize?oauth_token=%@" 
#define base_url @"http://api.tumblr.com/v2/user/XXXXXXXXXXXXX.tumblr.com/info" 
#define user_info @"http://api.tumblr.com/v2/user/info" 

@interface ViewController() 

@end 

@implementation ViewController 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
} 




- (IBAction)postIt:(id)sender 
{ 

    NSURL *postURL = [NSURL URLWithString:@"http://api.tumblr.com/v2/blog/xxxxxxxx.tumblr.com/post"]; 
    OAMutableURLRequest *oRequest = [[OAMutableURLRequest alloc] initWithURL:postURL 
                    consumer:self.consumer 
                     token:self.accessToken 
                     realm:nil 
                  signatureProvider:nil]; 
    [oRequest setHTTPMethod:@"POST"]; 

    [oRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

    OARequestParameter *statusParam = [[OARequestParameter alloc] initWithName:@"body" 
                     value:@"Sample Body"]; 
    OARequestParameter *statusParam2 = [[OARequestParameter alloc] initWithName:@"type" 
                     value:@"text"]; 

    NSArray *params = [NSArray arrayWithObjects:statusParam,statusParam2, nil]; 
    [oRequest setParameters:params]; 
    OAAsynchronousDataFetcher *fetcher = [OAAsynchronousDataFetcher asynchronousFetcherWithRequest:oRequest 
                          delegate:self 
                       didFinishSelector:@selector(sendStatusTicket:didFinishWithData:) 
                        didFailSelector:@selector(sendStatusTicket:didFailWithError:)]; 
    NSLog(@"URL = %@",[oRequest.URL absoluteString]); 

    [fetcher start]; 
} 


- (void)didReceiveAccessToken:(OAServiceTicket *)ticker data:(NSData *)responseData 
{ 


} 

- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error { 
    // ERROR! 
} 




- (void)sendStatusTicket:(OAServiceTicket *)ticker didFinishWithData:(NSData *)responseData 
{ 
    if (ticker.didSucceed) { 
     NSLog(@"Success"); 
    } 
    NSString *responseBody = [[NSString alloc] initWithData:responseData 
                encoding:NSUTF8StringEncoding]; 

    NSLog(@"Description = %@",responseBody); 


} 
- (void)sendStatusTicket:(OAServiceTicket *)ticker didFailWithError:(NSError *)error 
{ 
    NSLog(@"Error = %@",[error localizedDescription]); 
} 
- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return YES; 
} 

- (IBAction)login:(id)sender 
{ 
    self.consumer = [[OAConsumer alloc] initWithKey:consumer_key secret:consumer_secret]; 

    NSURL *url = [NSURL URLWithString:request_token_url]; 


    OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url 
                    consumer:self.consumer 
                     token:nil // we don't have a Token yet 
                     realm:nil // our service provider doesn't specify a realm 
                  signatureProvider:nil]; // use the default method, HMAC-SHA1 

    [request setHTTPMethod:@"POST"]; 

    OADataFetcher *fetcher = [[OADataFetcher alloc] init]; 

    [fetcher fetchDataWithRequest:request 
         delegate:self 
       didFinishSelector:@selector(requestTokenTicket:didFinishWithData:) 
        didFailSelector:@selector(requestTokenTicket:didFailWithError:)]; 


} 
- (void)requestTokenTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data { 
    if (ticket.didSucceed) 
    { 
     NSString *responseBody = [[NSString alloc] initWithData:data 
                 encoding:NSUTF8StringEncoding]; 
     self.accessToken= [[OAToken alloc] initWithHTTPResponseBody:responseBody]; 

     NSURL *author_url = [NSURL URLWithString:[ NSString stringWithFormat:authorize_url,self.accessToken.key]]; 
     OAMutableURLRequest *oaR = [[OAMutableURLRequest alloc] initWithURL:author_url consumer:nil token:nil realm:nil signatureProvider:nil];   
     UIWebView *webView =[[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds]; 
     [[[UIApplication sharedApplication] keyWindow] addSubview:webView]; 
     webView.delegate=self; 
     [webView loadRequest:oaR]; 

    } 
} 

// This is to get oAuth_verifier from the url 

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { 

    NSString *url = [[request URL] absoluteString]; 
    NSString *keyOne = @"oauth_token"; 
    NSString *keyTwo = @"oauth_verifier"; 
    NSRange r1 =[url rangeOfString:keyOne]; 
    NSRange r2 =[url rangeOfString:keyTwo]; 
    if (r1.location!=NSNotFound && r2.location!=NSNotFound) { 
     // Extract oauth_verifier from URL query 
     NSString* verifier = nil; 
     NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:@"&"]; 
     for (NSString* param in urlParams) { 
      NSArray* keyValue = [param componentsSeparatedByString:@"="]; 
      NSString* key = [keyValue objectAtIndex:0]; 
      if ([key isEqualToString:@"oauth_verifier"]) { 
       verifier = [keyValue objectAtIndex:1]; 
       break; 
      } 
     } 
     if (verifier) { 
      NSURL* accessTokenUrl = [NSURL URLWithString:@"http://www.tumblr.com/oauth/access_token"]; 
      OAMutableURLRequest* accessTokenRequest =[[OAMutableURLRequest alloc] initWithURL:accessTokenUrl 
                        consumer:self.consumer 
                         token:self.accessToken 
                         realm:nil 
                      signatureProvider:nil]; 
      OARequestParameter* verifierParam =[[OARequestParameter alloc] initWithName:@"oauth_verifier" value:verifier]; 
      [accessTokenRequest setHTTPMethod:@"POST"]; 
      [accessTokenRequest setParameters:[NSArray arrayWithObjects:verifierParam,nil]]; 
      OADataFetcher* dataFetcher = [[OADataFetcher alloc] init]; 
      [dataFetcher fetchDataWithRequest:accessTokenRequest 
            delegate:self 
          didFinishSelector:@selector(requestTokenTicketForAuthorization:didFinishWithData:) 
           didFailSelector:@selector(requestTokenTicket:didFailWithError:)]; 
     } else { 
      // ERROR! 
     } 
     [webView removeFromSuperview]; 
     return NO; 
    } 
    return YES; 
} 


- (void)requestTokenTicketForAuthorization:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data 
{ 
    if (ticket.didSucceed) 
    { 
     NSString *responseBody = [[NSString alloc] initWithData:data 
                 encoding:NSUTF8StringEncoding]; 
     self.accessToken = [self.accessToken initWithHTTPResponseBody:responseBody]; 
     accessText=self.accessToken.key; 
     accessSecret=self.accessToken.secret; 
    } 
    else 
    { 
     NSString *responseBody = [[NSString alloc] initWithData:data 
                 encoding:NSUTF8StringEncoding]; 
     NSLog(@"Response = %@",responseBody); 
    } 


} 
- (void)requestTokenTicket:(OAServiceTicket *)ticket didFailWithError:(NSError *)error 
{ 
    NSLog(@"Error = %@",[error localizedDescription]); 
} 


@end 

Tôi đã nhầm lẫn gì ở đây? Tại sao tôi nhận được lỗi đó? Tôi có làm theo các bước đúng cách không?

Trả lời

3

Vui lòng XXX ra khỏi consumer_key và consumer_secret của bạn để tránh việc sử dụng chúng không mong muốn. Mã khôn ngoan có một vài điều bạn có thể muốn tìm ở đây.

  1. Bạn có thể sử dụng yêu cầu oauth 'GET' chẳng hạn như "http://api.tumblr.com/v2/user/info" không? Nếu bạn có thể nhận được yêu cầu 'GET' thành công thì mã thông báo truy cập của bạn là hợp lệ và bạn có thể xem cách bạn đang gửi thông số bài đăng của mình.

  2. Đảm bảo bạn chuyển các tham số của mình dưới dạng Thông số cơ thể HTTP cũng như thông số chữ ký. Sắp xếp thông số chính xác có thể được cung cấp bởi thư viện.

    NSString * postbody = @ "body = myBodyText & type = text";

    [oRequest setHTTPBody: [dữ liệu bài đăngSử dụng Mã hóa: NSUTF8StringEncoding allowLossyConversion: TRUE]];

+0

@jduellert .. Cảm ơn bạn rất nhiều !! – Bharath

Các vấn đề liên quan