NSURLSession(二)POST请求

来源:互联网 发布:java 是干嘛的 编辑:程序博客网 时间:2024/06/10 20:44
//1.构造URL
NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/2/statuses/update.json"];

//2.构造Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//(1)设置为POST请求
[request setHTTPMethod:@"POST"];

//(2)超时
[request setTimeoutInterval:60];

//(3)设置请求头
//[request setAllHTTPHeaderFields:nil];

//(4)设置请求体
//发新浪微博
//请求体里需要包含至少两个参数
//指定用户的令牌 微博正文
//access_token status
//这里的 access_token 大家可以用自己的微博来测试 access_token->是通过自己的微博账号密码生成的 具体流程可以参照 http://www.cnblogs.com/ok-lanyan/archive/2012/07/15/2592070.html
NSString *bodyStr = @"access_token=xxxxx&status=微博内容";

NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

//设置请求体

[request setHTTPBody:bodyData];



//3.构造Session
NSURLSession *session = [NSURLSession sharedSession];

//4.task
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"response : %@", response);
}];

//5.
[task resume];


0 0