iOS 微博 OAuth2.0 分享文字微博的方法

这里以新浪的为例子进行说明,后面会陆续添加;

这里同时提供两种方式,一种是通过ASIFormData的方式来完成

NSURL *url = [[NSURLalloc] initWithString:@"https://api.weibo.com/2/statuses/update.json"];

//    statuses/upload

    ASIFormDataRequest *request = [[ASIFormDataRequestalloc] initWithURL:url];

    NSUserDefaults *info = [NSUserDefaultsstandardUserDefaults];

 

    [request addPostValue:SINAAPPKEY forKey:@"source"];

    [request addPostValue:Text forKey:@"status"];

    [request addPostValue:@"0" forKey:@"lat"];

    [request addPostValue:@"0" forKey:@"long"];

    [request addPostValue:[selfDecrypt:MyPWDKey :[info objectForKey:@"sina_access_tokenV2"]] forKey:@"access_token"];

 

    [request startSynchronous];

    NSString *rst = [request responseString];

    [request release];

    [url release];

 

另一个种是通过iOS SDK 来实现

NSAutoreleasePool *pool = [[NSAutoreleasePoolalloc] init];

 

    NSUserDefaults *info = [NSUserDefaultsstandardUserDefaults];

    NSString *post=[NSStringstringWithFormat:@"source=%@&status=%@&lat=0&long=0&access_token=%@",SINAAPPKEY,sinaWeiBoText,[selfDecrypt:MyPWDKey :[info objectForKey:@"sina_access_tokenV2"]]];

    

    NSData *postData=[post dataUsingEncoding:NSUTF8StringEncodingallowLossyConversion:YES];

    NSString *postLength=[NSString stringWithFormat:@"%d",[postData length]];

    

    NSMutableURLRequest *request=[[NSMutableURLRequestalloc] initWithURL:[NSURLURLWithString:SINASENDTEXT]];

    [request setHTTPMethod:@"POST"];

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

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

    [request setHTTPBody:postData];

    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (conn)    

    {

        NSURLResponse *response;

        NSError *error;

        

        NSData *resutlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSString *resultSting=[[NSStringalloc] initWithData:resutlData encoding:NSUTF8StringEncoding];

        NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:[resultSting JSONValue]];

        NSLog(@"%@",dict);

        if ([dict objectForKey:@"error_code"] != nil) {

            int code = [[dict objectForKey:@"error_code"] intValue];

            NSLog(@"code = %d",code);

            if (code == 20019) {

                [self showMessage:@"不能发布相同的微博!"];

            }

            else {

                [self showMessage:@"发送微博失败!"];

            }

        }

        else {

            [self showMessage:@"分享新浪微博成功!"];

        }

        

        [resultSting release];

        [dict release];

    }

    [conn release];

    [request release];

    [pool release];

 

 

第一种方式更为简洁

 

原文地址:https://www.cnblogs.com/easonoutlook/p/2642783.html