在iOS中,常见的发送HTTP请求的方案有

苹果原生(自带)

  1. NSURLConnection:用法简单,最古老最经典的一种方案
  2. NSURLSession:功能比NSURLConnection更加强大,推荐使用这种技术(2013年推出)
  3. CFNetwork:NSURL的底层,纯C语言

第三方框架

  1. ASIHttpRequest:外号:“HTTP终结者”,功能及其强大,早已不维护
  2. AFNETworking:简单易用,提供了基本够用的常用功能,维护和使用者居多
  3. MKNetworkKit:简单易用,来自印度,维护使用者少

建议

为了提高开发效率,企业开发用的基本是第三方框架

一.使用NSURLConnection

NSURLConnection常见的发送请求方法有以下几种
 
//同步请求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
//异步请求:根据对服务器返回数据的处理方式的不同,又可以分为2种
//block回调
+ (void)sendAsynchronousRequest:(NSURLRequest*) request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler; //代理
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;

代理相关的方法

#pragma mark -NSURLConnectionDelegate - begin

/**
请求失败(比如请求超时)
*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { } /**
接收到服务器的响应
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiverResponse");
//初始化
self.responseData = [NSMutableData data];
} /**
接收到服务器的数据(如果数据量比较大,这个方法会调用多次)
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"didReceiveData - %zd",data.length);
//拼接
[self.responseData appendData:data];
} /**
服务器的数据成功,接收完毕
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
//显示数据
NSString *str = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@",str); }

二.使用NSURLSession

使用NSURLSession对象创建Task,然后执行Task

1.使用NSURLSessionDataTask

post请求

- (void)post {

    //获取NSURLSession对象
NSURLSession *session = [NSURLSession sharedSession]; //创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_01.png"]];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding]; //创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}]; //启动任务
[task resume]; }

get请求

- (void)get {
NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); }]; //启动
[task resume];
}

代理方法

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];

    NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"]];

    //启动
[task resume];
} #pragma mark -<NSURLSessionDataDelegate> /**
* 1.接收到服务器的响应
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
NSLog(@"----%s----",__func__); //允许处理服务器的响应
completionHandler(NSURLSessionResponseAllow);
} /**
* 2.接收到服务器的数据(可能会被调用多次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSLog(@"----%s----",__func__);
} /**
* 3.请求成功或者失败(如果失败,error有值)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"----%s----",__func__);
}

二.使用AFNetworking框架

网址:https://github.com/AFNetworking/AFNetworking

AFHTTPRequestOperationManager内部包装了NSURLConnection

- (void)get {
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; NSDictionary *params = @{
@"username" : @"520it",
@"pwd" : @"520it"
}; [mgr GET:@"http://120.25.226.186:32812/login" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"请求成功----%@",[responseObject class]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败----%@",error);
}];
}

AFHTTPSessionManager内部包装了NSURLSession

- (void)get2 {

    //AFHTTPSessionManager内部包装了NSURLSession
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager]; NSDictionary *params = @{
@"username" : @"520it",
@"pwd" : @"520it"
}; [mgr GET:@"http://120.25.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"请求成功----%@",[responseObject class]); } failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"请求失败----%@",error);
}];
}

AFN这个框架默认使用了JSON解析器,如果服务器返回的是XML格式的

你需要将框架中的解析器换成XML解析器

    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

    //responseSerializer 用来解析服务器返回的数据
//告诉AFN 以XML形式解析服务器返回的数据
mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];

iOS中发送HTTP请求的方案的更多相关文章

  1. Vue中发送ajax请求——axios使用详解

    axios 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用 功能特性 在浏览器中发送 XMLHttpRequests 请求 在 node.js 中发送 htt ...

  2. IE6—在链接click事件的响应函数中发送jsonp请求不生效

    $("#link").click(function(){     $.ajax({         type: 'GET',         dataType: 'jsonp', ...

  3. 如何在WinForm中发送HTTP请求

    如何在WinForm中请求发送HTTP 手工发送HTTP请求主要是调用 System.Net的HttpWebResponse方法 手工发送HTTP的GET请 求: string strURL = &q ...

  4. IOS中DES与MD5加密方案

      0 2 项目中用的的加密算法,因为要和安卓版的适配,中间遇到许多麻烦. MD5算法和DES算法是常见的两种加密算法. MD5:MD5是一种不可逆的加密算法,按我的理解,所谓不可逆,就是不能解密,那 ...

  5. golang中发送http请求的几种常见情况

    整理一下golang中各种http的发送方式 方式一 使用http.Newrequest 先生成http.client -> 再生成 http.request -> 之后提交请求:clie ...

  6. iOS中几种数据持久化方案

    概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据.在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案: plist文件(属性列表) ...

  7. rails中发送ajax请求

    最近在写一个blog系统练练手,遇到一个一个问题,用户添加评论的时候想发送ajax请求,但是rails里的ajax和Python中的不太一样,Python中的ajax是用js,jquery实现的和ra ...

  8. iOS中几种数据持久化方案:我要永远地记住你!

    http://www.cocoachina.com/ios/20150720/12610.html 作者:@翁呀伟呀 授权本站转载 概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启 ...

  9. java中发送http请求的方法

    package org.jeecgframework.test.demo; import java.io.BufferedReader; import java.io.FileOutputStream ...

随机推荐

  1. Android debug时一直处于waiting for debugger解决办法

    问题:android 调试卡在:Waiting for Debugger - Application XXX is waiting for the debugger to Attach" 解 ...

  2. C#/C++ 中字节数组与int类型转换

    1.C#中int和byte[]转换: /// <summary> /// 把int32类型的数据转存到4个字节的byte数组中 /// </summary> /// <p ...

  3. ruby -- 进阶学习(九)定制错误跳转404和500

    在开发阶段,如果发生错误时,都会出现错误提示页面,比如:RecordNotFound之类的,虽然这些错误方便开发进行debug,但是等产品上线时,如果还是出现这些页面,对于用户来说是很不友好的. 所以 ...

  4. google翻译,翻译当前的网页

    网页翻译为德语(Translate Page To German) <a href="javascript: void(window.open('http://translate.go ...

  5. 编写高质量JS代码的68个有效方法(三)

    [20141030]编写高质量JS代码的68个有效方法(三) *:first-child { margin-top: 0 !important; } body>*:last-child { ma ...

  6. 轻量型ORM框架Dapper的使用

    在真实的项目开发中,可能有些人比较喜欢写SQL语句,但是对于EF这种ORM框架比较排斥,那么轻量型的Dapper就是一个不错的选择,即让你写sql语句了,有进行了关系对象映射.其实对于EF吧,我说下我 ...

  7. 用于软件包管理的21个Linux YUM命令 转载

    http://flycars001.iteye.com/blog/1949085 YUM到底是啥东东? YUM(Yellowdog Updater Modified)是一款开源命令行及图形化软件包管理 ...

  8. selenium webdriver (python) 第三版

    感谢 感谢购买第二版的同学,谢谢你们对本人劳动成果的支持!也正是你们时常问我还出不出第三版了,也是你们的鼓励,让我继续学习整理本文档. 感谢乙醇前辈,第二版的文档是放在他的淘宝网站上卖的,感谢他的帮忙 ...

  9. [python]decimal常用操作和需要注意的地方

    decimal模块 简介 decimal意思为十进制,这个模块提供了十进制浮点运算支持. 常用方法 1.可以传递给Decimal整型或者字符串参数,但不能是浮点数据,因为浮点数据本身就不准确. 2.要 ...

  10. suricata学习笔记1--初步认识

    1.前言  最近工作需要对网站的关键字进行检测,找出敏感词.这个过程需要对报文进行收集.解码.检测和记录日志.当前只是简单实现功能,根据关键字进行简单的匹配,而没有进行关键字的语义分析.导致的结果就是 ...