一: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. Alvin

    Alvin Zhao 東京都 港区虎ノ門2-10-4 ホテルオークラ東京 M 663 電話番号: 0335820111

  2. JAVA简单工厂模式(从现实生活角度理解代码原理)

    简单工厂模式(Simple Factory),说他简单是因为我们可以将此模式比作一个简单的民间作坊,他们只有固定的生产线生产固定的产品.也可以称他为静态工厂设计模式,类似于之前提到过静态代理设计模式, ...

  3. iOS UIPageViewController

    UIPageViewController是App中常用的控制器.它提供了一种分页效果来显示其childController的View.用户可以通过手势像翻书一样切换页面.切换页面时看起来是连续的,但静 ...

  4. NSCopy&NSMutableCopy

    struct student { int a; float f; char c; long l; }; struct person { int a; float f; char c; long l; ...

  5. ObjectAnimator属性动画应用demo

    感谢慕课网--eclipse_xu 布局文件:activity_main.xml <FrameLayout xmlns:android="http://schemas.android. ...

  6. OC KVC

    OC KVC KVC 全称 key valued coding 键值编码 在说KVC之前应该简单的了解一下反射机制 反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法. 对于任意 ...

  7. SQLServer中的页如何影响数据库性能 (转)

    无论是哪一个数据库,如果要对数据库的性能进行优化,那么必须要了解数据库内部的存储结构.否则的话,很多数据库的优化工作无法展开.对于对于数据库管理员来说,虽然学习数据库的内存存储结构比较单调,但是却是我 ...

  8. MySQL慢查询Explain Plan分析

    Explain Plan 执行计划,包含了一个SELECT(后续版本支持UPDATE等语句)的执行 主要字段 id 编号,从1开始,执行的时候从大到小,相同编号从上到下依次执行. Select_typ ...

  9. UNIX系统的显示时间何时会到达尽头

    本文分为三个小块: 一.UNIX系统中时间的存储形式: 二. time_t 的最大值是多少: 三. 将time_t 的最大值转化为真实世界的时间: #---------------------# # ...

  10. 再探banana

    在Solr图形化界面:除Hue之外的选择中列出了banana的如下一些不足,今天再次研究这些地方是否有方案可以解决. 1.sunburst图功能没法用. 2.中文有些地方会显示%2B%4C之类的一串字 ...