IOS基于http的网络编程

HTTP定义了一种在服务器和客户端之间传递数据的途径。

URL定义了一种唯一标示资源在网络中位置的途径。

REQUESTS 和 RESPONSES:

客户端先建立一个TCP连接,然后发送一个请求。服务器受到请求处理后发送一个响应向客户端传递数据。然后客户端可以继续发送请求或者关闭这个TCP连接。

HTTPS:
在TCP连接建立后,发送请求之前,需要建立一个一个SSL会话。

request方法和它们的用途

注意:想server发送大量数据需要用POST,因为GET仅支持发送少量数据(8KB)。

iOS的NSURLRequest和它的子类NSMutableURLRequest提供了建立HTTP请求的方法。

NSURLResponse 和 它的子类NSHTTPURLResponse 处理返回的数据。

URL:

Protocol包括HTTP、FTP和file。

URL编码:

NSString *urlString = @"http://myhost.com?query=This is a question"; NSString *encoded = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL用来管理URL。

IOS HTTP APIS:

涉及到下面一些类:

NSURL, NSURLRequest, NSURLConnection, 和 NSURLResponse.

1、NSURL

NSURL可以定义本地文件和网络文件

NSURL *url = [NSURL urlWithString:@"http://www.google.com"]; 
NSData *data = [NSData dataWithContentsOfURL:url];

NSURL定义了很多访问器:

if (url.port == nil) {   NSLog(@"Port is nil");
} else {
  NSLog(@"Port is not nil");
}

2、NSURLRequest

创建了NSURL后,就可以用NSURLRequest建立请求了:

NSURL *url = [NSURL URLWithString: @"https://gdata.youtube.com/feeds/api/standardfeeds/top_rated"];
if (url == nil) {
     NSLog(@"Invalid URL"); 

   return;
}
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

if (request == nil) {
  NSLog(@"Invalid Request");
    return;
}

NSMutableURLRequest是NSURLRequest 的子类,提供了改变请求的属性的方法:

NSURL *url = [NSURL urlWithString@"http://server.com/postme"]; NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; [req setHTTPMethod:@"POST"];
[req setHTTPBody:[@"Post body" dataUsingEncoding:NSUTF8StringEncoding]];

如果你要发送一个图片或者视频,那么用需要用NSInputStream,它没有把数据全部加在到内存。

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:srcFilePath];
[request setHTTPBodyStream:inStream];
[request setHTTPMethod:@"POST"];

3、NSURLResponse

4、NSURLConnection

提供了初始化、开始、和取消一个连接。

发送同步请求:

- (NSArray *) doSyncRequest:(NSString *)urlString {
    // make the NSURL object from the string
    NSURL *url = [NSURL URLWithString:urlString];

    // Create the request object with a 30 second timeout and a cache policy to always retrieve the
    // feed regardless of cachability.
    NSURLRequest *request =
       [NSURLRequest requestWithURL:url
                        cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                    timeoutInterval:30.0];

    // Send the request and wait for a response
    NSHTTPURLResponse   *response;
    NSError             *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];
    // check for an error
    if (error != nil) {
        NSLog(@"Error on load = %@", [error localizedDescription]);
        return nil;
    }

    // check the HTTP status
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if (httpResponse.statusCode != 200) {
            return nil;
        }
        NSLog(@"Headers: %@", [httpResponse allHeaderFields]);
    }

    // Parse the data returned into an NSDictionary
    NSDictionary *dictionary =
        [XMLReader dictionaryForXMLData:data
                                  error:&error];
    // Dump the dictionary to the log file
    NSLog(@"feed = %@", dictionary);

    NSArray *entries =[self getEntriesArray:dictionary];

    // return the list if items from the feed.
    return entries;

}

Queued Asynchronous Requests:

- (void) doQueuedRequest:(NSString *)urlString  delegate:(id)delegate {
    // make the NSURL object
    NSURL *url = [NSURL URLWithString:urlString];

    // create the request object with a no cache policy and a 30 second timeout.
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];

    // If the queue doesn‘t exist, create one.
    if (queue == nil) {
        queue = [[NSOperationQueue alloc] init];
    }

    // send the request and specify the code to execute when the request completes or fails.
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data,
                                               NSError *error) {

            if (error != nil) {
               NSLog(@"Error on load = %@", [error localizedDescription]);
            } else {

                // check the HTTP status
                if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                    if (httpResponse.statusCode != 200) {
                        return;
                    }
                    NSLog(@"Headers: %@", [httpResponse allHeaderFields]);
                }

                // parse the results and make a dictionary
                NSDictionary *dictionary =
                   [XMLReader dictionaryForXMLData:data
                                             error:&error];
                NSLog(@"feed = %@", dictionary);

                // get the dictionary entries.
                NSArray *entries =[self getEntriesArray:dictionary];

                // call the delegate
                if ([delegate respondsToSelector:@selector(setVideos:)]) {
                    [delegate performSelectorOnMainThread:@selector(setVideos:)
                                               withObject:entries
                                            waitUntilDone:YES];
                }
            }
    }];
}

NSURLConnection start方法和Delegate:

GET:

 NSURL  *url=[[ NSURL   alloc ] initWithString :urlString];

     NSMutableURLRequest  *request=[[NSMutableURLRequest  alloc ] init ];

     NSURLConnection  *connection = [[ NSURLConnection   alloc ]  initWithRequest :request delegate : self ];
     if (connection)
     {
             [connection start];
         }
     else
     {
             NSLog ( @"sorry" );
     }

/*
* NSURLConnectionDataDelegate
*/
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{  [activityIndicator startAnimating]; //UIActivityIndicatorView
    NSLog(@"Did Receive Response %@", response);
    responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    //NSLog(@"Did Receive Data %@", data);
    [responseData appendData:data]; //NSMutableData
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    NSLog(@"Did Fail");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

   [activityIndicator stopAnimating];

    NSLog(@"Did Finish");
    // Do something with responseData
}

POST:

//initialize new mutable data
    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;

    //initialize url that is going to be fetched.
    NSURL *url = [NSURL URLWithString:@"http://www.snee.com/xml/crud/posttest.cgi"];

    //initialize a request from url
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];

    //set http method
    [request setHTTPMethod:@"POST"];
    //initialize a post data
    NSString *postData = [[NSString alloc] initWithString:@"fname=example&lname=example"];
    //set request content type we MUST set this value.

    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    //set post data of request
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];

    //initialize a connection from request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.connection = connection;
    //start the connection
    [connection start];

异步请求:
异步请求需要一个run loop来操作代理对象,GCD和NSOperationQueue默认并没有run loop,所以如果你想在后台发起一个HTTP请求,必须确保有run loop。

NSURLConnection connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];

上面的代码是在主线程运行,如果想在其他线程运行,可以在其他线程新建一个run loop,并绑定到connection。

时间: 2024-08-10 23:26:15

IOS基于http的网络编程的相关文章

Java网络编程和NIO详解9:基于NIO的网络编程框架Netty

Java网络编程和NIO详解9:基于NIO的网络编程框架Netty 转自https://sylvanassun.github.io/2017/11/30/2017-11-30-netty_introduction/ netty是基于NIO实现的异步事件驱动的网络编程框架,学完NIO以后,应该看看netty的实现,netty框架涉及的内容特别多,这里只介绍netty的基本使用和实现原理,更多扩展的内容将在以后推出. 本系列文章首发于我的个人博客:https://h2pl.github.io/ 欢迎

基于Socket实现网络编程

Socket是网络上两个程序间双向通讯的一端,它既可以发送请求,也可以接收请求,利用它可以方便的编写网络上数据的传递,在java中,有专门的类类处理用户的请求和响应.利用Socket 类的方法,就可以实现两台计算机之间的通信,那么怎么利用socket进行网络编程呢?我试试水~ 网络中的进程之间是如何进行通信的? 本地进程间通信(IPC)有很多种方法,简而言之可以归结为以下四类: 消息传递(管道,FIFO,消息队列); 同步(互斥量,条件变量,读写锁,文件和写记录锁,信号量): 内存共享(匿名的和

iOS UI高级之网络编程(HTTP协议)

HTTP协议的概念 HTTP协议,Hyper Text Transfer Protocol (超文本传输协议)是用于从万维网服务器传送超文本到本地浏览器的传输协议,HTTP是一个应用层协议,由请求和响应构成,是一个标准的客户端服务器模型 了解C/S模式 Client(客户端)和Server(服务器)常常分别处在相距很远的两台计算机上,Client程序的任务是将用户的要求提交给Server程序,再将Server程序返回的结果以特定的形式显示给用户:Server程序的任务是接受客户程序提出的服务请求

Java学习总结(十三)——基于UDP协议网络编程

一.UDP网络编程1.面向无连接的数据传输,不可靠的,但效率高(音频,视频等).2.UDP一次发送的数据不能超过64kb.3.UDP编程所需要的类(1)DatagramSocket此类表示用来发送和接收数据报包的套接字(2)DatagramPacket此类表示数据报包方法:DatagramPacket(byte[]?buf, int?length, InetAddress?address, int?port)参数表示:buf - 包数据length - 包长度address - 目的地址port

Java中基于HTTP协议网络编程

java中为我们的网络支持提供了java.net包,能够使我们以编程的方式来訪问Web服务功能,这篇博客,就跟大家分享一下.Java中的网络编程的知识.主要是学习下该java.net包下的API. URI-->URL URI:表示的是统一的资源标识,它是以某种统一的方式标识资源的简单字符串. 这样的字符串以scheme开头. URL:表示统一的资源定位器的任务,URL是一种URI. URN:一般不能为资源提供持久不变的名称.这是统一的资源命名的任务.URN也是一种URI,但它是全球唯一的.持久不

【转】libevent和基于libevent的网络编程

转自: http://www.cnblogs.com/nearmeng/p/4043548.html 1 libevent介绍和安装 介绍 libevent是一个轻量级的基于事件驱动的高性能的开源网络库,并且支持多个平台,对多个平台的I/O复用技术进行了封装,当我们编译库的代码时,编译的脚本将会根据OS支持的处理事件机制,来编译相应的代码,从而在libevent接口上保持一致. 在当前的服务器上,面对的主要问题就是要能处理大量的连接.而通过libevent这个网络库,我们就可以调用它的API来很

iOS开发之AFNetworking网络编程

众所周知,苹果搞的一套框架NSContention发送请求与接收请求的方式十分繁琐.操作起来很不方便.不仅要做区分各种请求设置各种不同的参数,而且还要经常在多线程里操作,同时还要对请求与返回的数据做各种序列化的操作,同时还要考虑请求数据的安全等一堆问题. 转载请注明出处:http://blog.csdn.net/xn4545945  一.早前的几个网络框架 1.ASI框架: HTTP终结者.很牛, 但是有BUG, 已经停止更新. 2.MKNetworkKit (印度人写的). 3.AFN一直还在

基于UDP的网络编程

与TCP编程相比较,UDP缺少了connect().listen()及accept()函数,这是由于UDP协议无连接的特性,不用维护TCP的连接.断开等状态. UDP编程框图

基于 Qt的网络编程

主要参考:http://blog.csdn.net/zouxy09/article/details/9140881