NSURLSession(二)POST请求

来源:互联网 发布:淘宝日用百货店铺推荐 编辑:程序博客网 时间:2024/05/19 14:39

(自iOS9.0起,NSURLConnection.sendSynchronousRequest被废除不用了。建议改用NSURLSession的dataTaskWithRequest方法。具体用法可以参考我的另一篇文章:Swift - 使用NSURLSession同步获取数据(通过添加信号量)
原文出自:www.hangge.com  转载请保留原文链接:http://www.hangge.com/blog/cache/detail_779.html

//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