zoukankan      html  css  js  c++  java
  • 网络接口 使用NSURLConnection完成Get和Post方法

    网络接口 使用NSURLConnection完成Get和Post方法

    什么是URL:

    URL就是统一资源定位器(UniformResourceLocator:URL)。通俗地说,它是用来指出某一项信息的所在位置及存取方式;更严格一点来说,URL就是在WWW上指明通讯协议以及定位来享用网络上各式各样的服务功能。

    这个URL一般分为两个部分:

    第一部分:

    模式/协议scheme它告诉浏览器如何处理将要打开的文件最常用的模式是超文本传输协议Hypertext TransferProtocol缩写为HTTP这个协议可以用来访问网络

    第二部分:

    文件所在的服务器的名称或IP地址后面是到达这个文件的路径和文件本身的名称服务器的名称或IP地址后面有时还跟一个冒号和一个端口号它也可以包含接触服务器必须的用户名称和密码路径部分包含等级结构的路径定义一般来说不同部分之间以斜线/分隔询问部分一般用来传送对服务器上的数据库进行动态询问时所需要的参数

    例如一个一般的URL接口为:http://ww1.sinaimg.cn/bmiddle/78c23a17jw1enanjhtsilj20c77fnb29.jpg

    Get和Post方法介绍:

    Get方法是直接讲参数放到了我们的路径的后面的,然后长度也有一定的限制,数据安全性不高。

    下面是一个get接口:

    http://xxxxx.yyyyyy.com:8001/mall/list.php?page2=1&cid=4

    前面和之前的那个接口一样,后面?之后是我们要上传的参数,多个参数之间,我们可以使用&隔开。

    Post方法是就相对复杂一点了,他将参数和路径分开来了。而且他的参数是没有限制的,然后安全性也比较高。

    其实这两个方法在参数比较小的时候,是可以相互转换的。我们将get中路径后面的参数放到了post中的参数体中,我们同样也可以调用这个接口里面的数据。


    简单概述网络接口调用方法的大致流程:

    1.创建一个NSString类型的path

    2.根据这个path创建一个NSURL类型的url

    3.通过url创建一个NSMutableURLRequest类型的request

    4.使用NSURLConnection中的方法来加载网络数据。


    网络接口调用方法代码及解释: 

    网络接口调用分为同步操作和异步操作;然后调用一个接口,我们一般可以使用post和get两种方法。这边通过四个例子来说明接口调用的四种操作:同步get操作,同步post操作,异步get操作和异步post操作。

    同步get操作:

      NSURLResponse *response;
        NSError *error;
        NSString *path = [NSString stringWithFormat:@"http://kaiyi.3tichina.com:8001/mall/list.php?page=1&catid=4"];
        NSURL *url = [NSURL URLWithString:path];
        NSMutableURLRequest *GetURLRequest = [[NSMutable URLRequestalloc] initWithURL:url];
       [GetURLRequest setHTTPMethod:@"GET"];
    NSData *data1 = [NSURLConnection sendSynchronousRequest:GetURLRequest returningResponse:&response error:&error];<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> </span>

    函数解释:这边我们使用了NSURLConnection的类方法来执行接口网络数据加载的操作:NSData *data1 =[NSURLConnection sendSynchronousRequest:GetURLRequest returningResponse:&response error:&error];

    然后我们将接口的获得的error,response,data信息都返回到了之前设置的变量中。

    异步get操纵:

    NSString *stirng = @"http://kaiyi.3tichina.com:8001/mall/list.php?page=1&catid=4";
        NSURL *url = [NSURLURLWithString:stirng];
        NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
       [request setHTTPMethod:@"GET"];
        NSOperationQueue *queue = [[NSOperationQueuealloc] init];
        __weak mianViewController *weakSelf = self;
        [NSURLConnection sendAsynchronousRequest:request queue:queuecompletionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError) {
           NSLog(@"responseis %@", response);
           NSLog(@"datais %@", data);
           NSLog(@"connectionErroris %@", connectionError);
           weakSelf.textDetail = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];
           dispatch_async(dispatch_get_main_queue(), ^{
    //界面的重新加载
               [weakSelf loadViewUI];
           });
           
    }];

    这个函数中,我们使用的接口调用方法是NSURLConnection的类方法,sendAsynchronousRequest,我们将请求数据设置,然后将异步操纵执行的队列设置好,然后将这些参数传入到sendAsynchronousRequest方法中去。这个方法就在异步执行了。需要注意的是,这个方法里面有一个代码块,我们将我们想要执行的操纵放到这个代码块中去,通过这种操作来调用接口中的参数。

    这里我们需要注意下我们在代码块中调用self时,我们使用的是weakself,因为如果我们直接使用self的话,这会在一定造成内存的丢失。

    还有就是如果我们想要对我们的界面进行操作的话,我们必须要返回我们的主线程中去。

     

    使用NSURLConnection代理方法来完成数据调用:

    -(void) loadDataofGetSysDelegate{
        NSString *path = [NSStringstringWithFormat:@"http://kaiyi.3tichina.com:8001/mall/list.php?page=1&catid=4"];
        NSURL *url = [NSURLURLWithString:path];
        NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
        [request setHTTPMethod:@"GET"];
        
        NSURLConnection *connection = [[NSURLConnectionalloc] initWithRequest:requestdelegate:self];
        [connection start];
    }

    通过上面的这两个方法

    NSURLConnection *connection = [[NSURLConnection allocinitWithRequest:request delegate:self];

        [connection start];

    我们完成了NSURLConnection的创建,接下来,我们就可以在NSURLConnection中完成我们提取数据操作了。

    NSURLConnection的代理方法有:

    @protocol NSURLConnectionDataDelegate <NSURLConnectionDelegate>
    @optional
    - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response;
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
    
    - (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request;
    - (void)connection:(NSURLConnection *)connection   didSendBodyData:(NSInteger)bytesWritten
                                                     totalBytesWritten:(NSInteger)totalBytesWritten
                                             totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite;
    
    - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse;
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection;
    @end

    Post方法同步加载数据

    NSString *path = @"http://kaiyi.3tichina.com:8001/member/userinfo.php";
        NSURL *url = [NSURLURLWithString:path];
        NSString *prama = [NSStringstringWithFormat:@"userid=1"];
        NSData *pramaData = [pramadataUsingEncoding:NSUTF8StringEncoding];
        NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
       request.HTTPMethod = @"POST";
       request.timeoutInterval = 5.0;
       request.HTTPBody = pramaData;
       
        NSURLConnection *connection = [[NSURLConnectionalloc] initWithRequest:requestdelegate:self startImmediately:YES];
        [connection start];
    

    其实,get方法和post方法是差不多的,get方法将参数放到了URL路径的后面,而post方法是将参数放到了HTTPBody方法中,这里我们需要注意下。我们设置post方法的时候,需要用NSMutableURLRequest的变量。


    下面是异步post操作:

      NSString *path =@"http://kaiyi.3tichina.com:8001/member/userinfo.php";
        NSURL *url = [NSURLURLWithString:path];
        NSString *param =@"userid=1";
        NSMutableURLRequest *request = [[NSMutableURLRequestalloc] initWithURL:url];
        request.HTTPMethod =@"POST";
        request.HTTPBody = [paramdataUsingEncoding:NSUTF8StringEncoding];
        
        NSOperationQueue *queue = [[NSOperationQueuealloc] init];
        [NSURLConnectionsendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError) {
            self.textDetail = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];
            dispatch_async(dispatch_get_main_queue(), ^{
                [selfloadViewUI];
            });
        }];
    


  • 相关阅读:
    Leetcode 1489找到最小生成树李关键边和伪关键边
    Leetcode 113 路径总和 II
    hdu 1223 还是畅通工程
    hdu 1087 Super Jumping! Jumping! Jumping!
    hdu 1008 Elevator
    hdu 1037 Keep on Truckin'
    湖工oj 1241 畅通工程
    湖工oj 1162 大武汉局域网
    hdu 2057 A + B Again
    poj 2236 Wireless Network
  • 原文地址:https://www.cnblogs.com/AbeDay/p/5026946.html
Copyright © 2011-2022 走看看