#ios和Android网络请求

引言

只说IOS和Android官方自带的网络请求,不说第三方框架.

IOS

介绍

An NSURLConnection object lets you load the contents of a URL by providing a URL request object. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request. You perform most of your configuration on the URL request object itself.

NSURLConnection通过提供一个URL request对象下载URL的内容,提供给NSURLConnection的接口是稀少的,只提供了控制开始和结束异步下载.但是可以对request object本身做更多的配置.

NSURLConnection只分异步和同步请求,如果要区分GET和POST请求,下面会说.

  • 同步请求

      + (NSData *)sendSynchronousRequest:(NSURLRequest *)request
               returningResponse:(NSURLResponse * _Nullable *)response
                           error:(NSError * _Nullable *)error
    
参数 解释
request 用来下载的URL request,这个request对象是深度复制的过程,当前方法的时候不会影响其他正在请求的进程.
response 返回response信息
error 请求时如果错误发生输出错误信息,可能是NULL
returnValue 返回的是NSData数据,即请求成功返回的数据

DEMO

NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"%@",data);
NSLog(@"继续执行");
  • 异步请求

      + (void)sendAsynchronousRequest:(NSURLRequest *)request
                        queue:(NSOperationQueue *)queue
            completionHandler:(void (^)(NSURLResponse *response,
                                        NSData *data,
                                        NSError *connectionError))handler
    
参数 解释
request 用来下载的URL request,这个request对象是深度复制的过程,当前方法的时候不会影响其他正在请求的进程.
queue 选择哪一个队列去处理当请求结束
handler 请求处理函数,就是回调函数

DEMO

NSURL *url=[NSURL URLWithString:@"http://apis.juhe.cn/mobile/get"];
NSURLRequest * request=[NSURLRequest requestWithURL:url];
NSOperationQueue    *queue =[NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
    //解析json
    NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    NSLog(@"%@",dict);
}];
  • GET 和 POST请求

    ios设置get或者post请求使用NSMutableURLRequest这个类来创建request,异步同步和上面,只需要替换request就行.

NSMutableURLRequest is a subclass of NSURLRequest provided to aid developers who may find it more convenient to mutate a single request object for a series of URL load requests instead of creating an immutable NSURLRequest object for each load.

NSMutableURLRequest是NSURLRequest的子类,是为了帮助开发者能够容易改造简单的请求,从而代替NSURLConnection.

DEMO: (block的方式异步,无法对请求进行监控)

- (void)NSURLConnectionSendAsynchronousPostRequest{
NSURL *url=[NSURL URLWithString:@"www.baidu.com"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
NSDictionary *dict=@{
                      @"key":@"0f91954955628c69dd7610ea9a5229ff",
                     @"dtype":@"json",
                     @"ps":@"100",
                      @"pno":@"2"
                        } ; //数据
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil ];
[request setHTTPBody:data];//设置http body传输的数据 json格式
NSOperationQueue   *queue =[NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
    //在这里做回调处理
    NSString *test1=[[NSString alloc] initWithData:data
                                         encoding:NSUTF8StringEncoding];
    NSLog(@"---%@",test1);

}];

}

DEMO (代理的方式,可以监控请求)
只需要实现下面的delgete,然后这样请求就行:
[NSURLConnection connectionWithRequest:request delegate:self];

    // 服务器开始给客户端回传数据,这个方法只会执行一次
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    // 服务器开始回传数据,客户端需要创建一个空的,可变的Data对象,用于存储每次获取的数据片段
    // @property (nonatomic,retain)NSMutableData * returnInfoData;
    self.returnInfoData = [[NSMutableData alloc]init];

    NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response;
    // 状态码
    NSLog(@"%ld",httpResponse.statusCode);
    // 响应报头
    NSLog(@"%@",httpResponse.allHeaderFields);

    NSLOG_FUNCTION;

}

// 客户端持续接收数据,data是数据片段,整个数据分段返回,这个方法执行的次数取决于数据总长度[response expectedContentLength]

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [_returnInfoData appendData:data];
    NSLOG_FUNCTION;
}


// 数据完全下载成功,接收到完整数据
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    // _returnInfoData 是完整的数据了

    [_returnInfoData release];
    NSLOG_FUNCTION;
}


// 数据下载失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    NSLog(@"didFailWithError");
    NSLOG_FUNCTION;

}

ios7之后提出用NSURLSession替代NSURLConnection.

The NSURLSession class and related classes provide an API for downloading content. This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended.

NSURLSession 类和相关类提供下载的api.这些api提供丰富的委托方法来处理后台下载的流程,当你的app中断或者无法运行.

  • NSURLSession :一个session对象
  • NSURLSessionConfiguration :当初始化session的配置对象
  • NSURLSessionTask :处理任务的基类
  • NSURLSessionDataTask:这个类是用来获取数据,将返回数据作为NSData返回
  • NSURLSessionUploadTask :上传文件的一个类
  • NSURLSessionDownloadTask :下载临时性的文件
  • NSURLSessionStreamTask:用来建立TCP/IP连接的

我们用NSURLSessionDataTask进行请求数据,所以我们使用NSURLSessionDataDelegate代理来请求.
NSURLSessionDataDelegate:

  • URLSession:dataTask:didReceiveResponse:completionHandler :告知代理任务获取到了服务器刚开始的回复

  • URLSession:dataTask:didBecomeDownloadTask:告知数据任务这个任务边为下载任务

  • URLSession:dataTask:didBecomeStreamTask:告知这个数据任务转变为下载stream的任务

  • URLSession:dataTask:didReceiveData:告知代理data任务已经获取期望的数据

  • URLSession:dataTask:willCacheResponse:completionHandler:询问代理数据任务返回的response是否要存到缓存中

DEMO:

    -(void)NSURLSessionDelgete{
    NSURL *url=[NSURL URLWithString:@"http://apis.juhe.cn/mobile/get"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
    NSDictionary *dict=@{
                         @"key":@"0f91954955628c69dd7610ea9a5229ff",
                         @"dtype":@"json",
                         @"ps":@"100",
                         @"pno":@"2"
                         } ; //数据
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil ];
    [request setHTTPBody:data];//设置http body传输的数据 json格式
    
    
    //代理的方法,主线程
    NSURLSession *session_1 = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate: self delegateQueue:[NSOperationQueue mainQueue]];
    
    //创建任务(因为要使用代理方法,就不需要block方法初始化)
    NSURLSessionDataTask *task_1 = [session_1 dataTaskWithRequest:request];
    //启动
    [task_1 resume];
}
//服务器开始响应,准备返回数据
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //运行出来服务器的响应
    completionHandler(NSURLSessionResponseAllow);
    //当网络请求是基于http协议的时候,response的本质为NSHTTPURLResponse
    //    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
    
    //初始化容器
    _mData = [NSMutableData data];
}

//客户端接收数据
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [_mData appendData:data];
}

//数据请求完成网络请求成功,当error不为空,说明响应出错
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (error) {
        NSLog(@"error -- %@",error);
    }
    else
    {
        NSString *str = [[NSString alloc]initWithData:_mData encoding:NSUTF8StringEncoding];
        NSLog(@"delegate  -- %@",str);
    }
}

Android

Android自带的有两种:

  • HttpClient (已经被弃用)
  • HttpURLConnection

所以我们只简单说一下HttpURLConnection.

同步异步:

Android中的同步只需要在主线程执行下面demo代码就行,异步就是new Thread()一个线程.

Demo:(通过建立连接,对输出输入流读写来传递和获取数据)

    HttpURLConnection conn = null;
                try {
                    // 创建一个URL对象
                    URL mURL = new URL(url);
                    // 调用URL的openConnection()方法,获取HttpURLConnection对象
                    conn = (HttpURLConnection) mURL.openConnection();

            conn.setRequestMethod("POST");// 设置请求方法为post
            conn.setReadTimeout(5000);// 设置读取超时为5秒
            conn.setConnectTimeout(10000);// 设置连接网络超时为10秒
            conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容

            // post请求的参数
            String data = content;
            // 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
            OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
            out.write(data.getBytes());
            out.flush();
            out.close();

            int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
            if (responseCode == 200) {

                InputStream is = conn.getInputStream();
                String response = getStringFromInputStream(is);
                return response;
            } else {
                throw new NetworkErrorException("response status is "+responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();// 关闭连接
            }
        }

你可能感兴趣的:(#ios和Android网络请求)