1.NSMutableURLRequest
NSMutableURLRequest是NSURLRequest的子类,常用方法
//设置请求超时等待时间(超过这个时间就算超时,请求失败)
- (void)setTimeoutInterval:(NSTimeInterval)seconds;
//设置请求方法(比如GET和POST)
- (void)setHTTPMethod:(NSString *)method;
//设置请求体
- (void)setHTTPBody:(NSData *)data;
//设置请求头
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
//创建GET请求
NSString *urlStr = [@"http://www.jianshu.com/users/468d1f0192cb/latest_articles" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//创建POST请求
NSString *urlStr = @"http://www.jianshu.com/users/468d1f0192cb/latest_articles";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 请求体
NSString *bodyStr = @"username=solozyx&pwd=solozyx";
request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
demo:
- (void)post {
// 1.请求路径
NSURL *url = [NSURL URLWithString:@"http://www.jianshu.com/users/468d1f0192cb/latest_articles"];
// 2.创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 更改请求方法
request.HTTPMethod = @"POST";
// 设置请求体
request.HTTPBody = [@"username=solozyx&pwd=solozyx" dataUsingEncoding:NSUTF8StringEncoding];
// 设置超时(5秒后超时)
request.timeoutInterval = 5;
// 设置请求头
[request setValue:@"iOS 9.0+" forHTTPHeaderField:@"User-Agent"];
// 3.发送请求
[NSURLConnection sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) { // 比如请求超时
NSLog(@"请求失败");
} else {
// 把得到的页面显示在webView
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSString *htmlStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"webView Code : %@",htmlStr);
}];
}
}];
}