一:NSURLConnection(IOS9.0已经弃用)是早期apple提供的http访问方式。以下列出了常用的几个场景:GET请求,POST请求,Response中带有json数据

对于NSURLConnection有以下注意事项:(1)sendAsynchronourequest: queue: completionHandler:函数中的queue参数表示的是“handler 这个block运行在queue中,如果queue为mainThread,那么hanlder就运行在主线程;所以在处理UI的时候需要注意这个参数”

(1)Get请求(返回文本)

  //Request
NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];
[urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php?namr&id=43"]];
[urlRequest setTimeoutInterval:10.0f];
[urlRequest setHTTPMethod:@"GET"];
[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

    //根据回复Headers,确认是是否为NSHTTPURLResponse的对象
   if([response isKindOfClass:[NSHTTPURLResponse class]]){
   NSHTTPURLResponse *resHttp = (NSHTTPURLResponse *)response;
   NSLog(@"status = %ld",resHttp.statusCode);//200 304 401......
   NSDictionary *dicHeader = resHttp.allHeaderFields;
  NSLog(@"headers = %@",dicHeader);
   }
   else{
   NSLog(@"not http");
  }
   if(data){
   NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
   NSLog(@"%@",html);
   }
}];
 
(2)POST请求(返回文本)
    //Request

    NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];

    [urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php"]];
[urlRequest setTimeoutInterval:10.0f];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
NSString *strBody = @"p1=abc&p2=12";
[urlRequest setHTTPBody:[strBody dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//确认是http
if([response isKindOfClass:[NSHTTPURLResponse class]]){
NSHTTPURLResponse *resHttp = (NSHTTPURLResponse *)response;
NSLog(@"status = %ld",resHttp.statusCode);//200 304 401......
NSDictionary *dicHeader = resHttp.allHeaderFields;
NSLog(@"headers = %@",dicHeader);
}
else{
NSLog(@"not http");
}
if(data){
NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",html);
}
}];

(3)Response中有Json数据

    //Request

    NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];

    [urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php"]];
[urlRequest setTimeoutInterval:10.0f];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
NSString *strBody = @"p1=abc&p2=12";
[urlRequest setHTTPBody:[strBody dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSError *err2 = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err2]; if([jsonObject isKindOfClass:[NSDictionary class]]){
NSLog(@"NSDictionary");
NSDictionary *dic = jsonObject;
NSLog(@"dic = %@",dic);
}
else if([jsonObject isKindOfClass:[NSArray class]]){
NSLog(@"NSDictionary");
NSDictionary *arr = jsonObject;
NSLog(@"arr = %@",arr);
}
}];

 

(4)Request中带有Json格式数据

    //Request
NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];
[urlRequest setURL:[NSURL URLWithString:@"http://XXXX.sinaapp.com/test/test.php"]];
[urlRequest setTimeoutInterval:10.0f];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];//这句没有也没关系 NSDictionary *dicRequest = @{@"name":@"leo",
@"id":@"456"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicRequest options:NSJSONWritingPrettyPrinted error:nil];
[urlRequest setHTTPBody:jsonData]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSError *err2 = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err2]; if([jsonObject isKindOfClass:[NSDictionary class]]){
NSLog(@"NSDictionary");
NSDictionary *dic = jsonObject;
NSLog(@"dic = %@",dic);
}
else if([jsonObject isKindOfClass:[NSArray class]]){
NSLog(@"NSDictionary");
NSDictionary *arr = jsonObject;
NSLog(@"arr = %@",arr);
} }];

  

服务器端的处理与返回(将request的值末尾加上_appending,然后返回)

<?php
header('Access-Control-Allow-Origin:*');
$json_string = $GLOBALS['HTTP_RAW_POST_DATA'];
$obj = json_decode($json_string);
//echo $obj->name;
//echo $obj->id;
$arr = array(
"name"=>$obj->name."_appending",
"id"=>$obj->id."_appending");
echo json_encode($arr);

  

(5)从服务器下载图片(启示就是普通的GET请求,只是将response中的data转为Image而已)

 //Request
NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];
[urlRequest setURL:[NSURL URLWithString:@"https://res.wx.qq.com/mpres/htmledition/images/pic/case-detail/nfhk_l23b6fe.jpg"]];
[urlRequest setTimeoutInterval:10.0f];
[urlRequest setHTTPMethod:@"GET"];
[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; [NSURLConnection
sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
UIImage *img = [UIImage imageWithData:data];
[self.imgView setImage:img];
}];

(6)以上所有动作都可以使用代理来做,原理上都是一样的

NSURLConnectionDataDelegate,

NSURLConnectionDelegate,

NSURLConnectionDownloadDelegate

 

NSURLConnection的使用的更多相关文章

  1. NSURLConnection实现文件上传和AFNetworking实现文件上传

    请求的步骤分为4步 1.创建请求 2.设置请求头(告诉服务器这是一个文件上传的请求) 3.设置请求体 4.发送请求 NSURLConnection实现文件上传 // 1.创建请求 NSURL *url ...

  2. iOS网络1——NSURLConnection使用详解

    原文在此 一.整体介绍 NSURLConnection是苹果提供的原生网络访问类,但是苹果很快会将其废弃,且由NSURLSession(iOS7以后)来替代.目前使用最广泛的第三方网络框架AFNetw ...

  3. NSURLConnection学习笔记

    虽说现在都用三方库来获取网络数据,再不济也会用苹果官方的NSURLSession,但有些东西还是要先学会才有资格说不好不用,不是么? NSURLConnection发送请求是分为同步和异步两种方式的, ...

  4. 网络第一节——NSURLConnection

    一.NSURLConnection的常用类 (1)NSURL:请求地址 (2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法.请求头.请求体.... ...

  5. post NSURLConnection请求网络数据

    #import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...

  6. NSURLConnection 异步加载网络数据

    #import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...

  7. iOS NSURLConnection POST异步请求封装,支持转码GBK,HTTPS等

    .h文件 #import <Foundation/Foundation.h> //成功的回调 typedef void(^successBlock)(id responseObj); // ...

  8. NSURLConnection使用

    *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...

  9. iOS开发 GET、POST请求方法(NSURLConnection篇)

    Web Service使用的主要协议是HTTP协议,即超文本传输协议. HTTP/1.1协议共定义了8种请求方法(OPTIONS.HEAD.GET.POST.PUT.DELETE.TRACE.CONN ...

随机推荐

  1. 推荐一个iOS关于颜色的库-Wonderful

    Wonderful 这个库主要是与UIColor息息相连的,其中一共包含四个子文件,UIColor+Wonderful,UIColor+Separate,SXColorGradientView,SXM ...

  2. LruCache缓存

    LruCache通常用于实现内存缓存,采用的缓存算法是LRU(Least Recently Used)即近期最少使用算法,其核心思想是:当缓存满的时候,会优先淘汰那些近期最少使用的缓存对象. 1.Lr ...

  3. AES 加密工具类

    /** * AES 是一种可逆加密算法,对用户的敏感信息加密处理 对原始数据进行AES加密后,在进行Base64编码转化: */public class AESOperator { /* * 加密用的 ...

  4. [Java编程思想-学习笔记]第3章 操作符

    3.1  更简单的打印语句 学习编程语言的通许遇到的第一个程序无非打印"Hello, world"了,然而在Java中要写成 System.out.println("He ...

  5. 5、软件架构师要阅读的书籍 - IT软件人员书籍系列文章

    软件架构师在项目中的地位是不言而喻的,其对于项目的需求要相对比较了解,然后对项目代码的结构需要做到覆盖全面.本文就说说作为一个软件架构师需要阅读的一些书籍. 当然,这些书籍都来源于网络,是笔者收集整理 ...

  6. ORACLE会话连接进程三者总结

    概念介绍 通俗来讲,会话(Session) 是通信双方从开始通信到通信结束期间的一个上下文(Context).这个上下文是一段位于服务器端的内存:记录了本次连接的客户端机器.通过哪个应用程序.哪个用户 ...

  7. .NET系列文章——近一年文章分类整理,方便各位博友们查询学习

    由于博主今后一段时间可能会很忙(准备出书:<.NET框架设计—模式.配置.工具>,外加换了新工作),所以博客会很少更新: 在最近一年左右时间里,博主各种.NET技术类型的文章都写过,根据博 ...

  8. redis 集群配置实战

    文章转载自:http://hot66hot.iteye.com/blog/2050676 最近研究Redis-cluster,正好搭建了一个环境,遇到了很多坑,系统的总结下,等到redis3 rele ...

  9. 关于 Java 数组的 12 个最佳方法

    1.  声明一个数组 String[] aArray = new String[5]; String[] bArray = {"a","b","c&q ...

  10. [原创]纯CSS3打造的3D翻页翻转特效

    刚接触CSS3动画,心血来潮实现了一个心目中自己设计的翻页效果的3D动画,页面纯CSS3,目前只能在Chrome中玩,理论上可以支持Safari. 1. 新建HTML,代码如下(数据和翻页后的数据都是 ...