26>ASI的基本使用

来源:互联网 发布:linux开机启动流程 编辑:程序博客网 时间:2024/05/16 03:02

1.利用ASI发送同步和异步请求代码:

////  ViewController.m//  02-ASI的基本使用////  Created by 张旗 on 15/5/21.//  Copyright (c) 2015年 张旗. All rights reserved.//#import "ViewController.h"#import "ASIHTTPRequest.h"@interface ViewController () <ASIHTTPRequestDelegate>@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {    [self asynGet];}/** *   发送异步的GET请求 */- (void)asynGet{    // 1. 创建一个连接    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"];    // 2. 创建一个请求    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];    // 设置代理    request.delegate = self;    // 3. 发送请求    [request startAsynchronous];}#pragma mark - ASIHTTPRequestDelegate中的方法/** *  1.开始发送请求 */- (void)requestStarted:(ASIHTTPRequest *)request{    NSLog(@"requestStarted");}/** *  2.接收到服务器的响应头信息 */- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders{    NSLog(@"didReceiveResponseHeaders");}/** *  3.接收到服务器的实体数据(具体数据) 只要实现了该方法,responseData\responseString就没有值 实现了这个方法,就意味着用户自己处理数据,系统不会去处理接收到的数据 *///- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data//{//   // NSLog(@"%@",data);//    NSLog(@"didReceiveData");//}/** * 4.服务器的响应数据接收完毕 */- (void)requestFinished:(ASIHTTPRequest *)request{    NSLog(@"%@",[request responseData]);    NSLog(@"requestFinished");}/** *  5.请求失败 */- (void)requestFailed:(ASIHTTPRequest *)request{    NSLog(@"requestFailed");}/** *  同步的get请求 */- (void)synGet{    // 1. 创建一个URL    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"];    // 2. 创建一个请求对象    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];    request.timeOutSeconds = 15; //设置超时时间    // 3. 开始请求    [request startSynchronous]; // 发送一个同步请求    // 4. 请求完毕    NSError *error = [request error];    if (error) {        NSLog(@"请求失败----%@",error);    }else{        /*         NSData *data = [request responseData];         NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];         */        NSString *str= [request responseString];        NSLog(@"请求成功----%@",str);    }}@end
0 0
原创粉丝点击