NSURLConnection的使用
一: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);
}
}];
//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的使用的更多相关文章
- NSURLConnection实现文件上传和AFNetworking实现文件上传
请求的步骤分为4步 1.创建请求 2.设置请求头(告诉服务器这是一个文件上传的请求) 3.设置请求体 4.发送请求 NSURLConnection实现文件上传 // 1.创建请求 NSURL *url ...
- iOS网络1——NSURLConnection使用详解
原文在此 一.整体介绍 NSURLConnection是苹果提供的原生网络访问类,但是苹果很快会将其废弃,且由NSURLSession(iOS7以后)来替代.目前使用最广泛的第三方网络框架AFNetw ...
- NSURLConnection学习笔记
虽说现在都用三方库来获取网络数据,再不济也会用苹果官方的NSURLSession,但有些东西还是要先学会才有资格说不好不用,不是么? NSURLConnection发送请求是分为同步和异步两种方式的, ...
- 网络第一节——NSURLConnection
一.NSURLConnection的常用类 (1)NSURL:请求地址 (2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法.请求头.请求体.... ...
- post NSURLConnection请求网络数据
#import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...
- NSURLConnection 异步加载网络数据
#import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...
- iOS NSURLConnection POST异步请求封装,支持转码GBK,HTTPS等
.h文件 #import <Foundation/Foundation.h> //成功的回调 typedef void(^successBlock)(id responseObj); // ...
- NSURLConnection使用
*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...
- iOS开发 GET、POST请求方法(NSURLConnection篇)
Web Service使用的主要协议是HTTP协议,即超文本传输协议. HTTP/1.1协议共定义了8种请求方法(OPTIONS.HEAD.GET.POST.PUT.DELETE.TRACE.CONN ...
随机推荐
- Fragment与ViewPager
众所周知,为了实现滑动界面,经常让Fragment与ViewPager一起结合使用,每一个ViewPager的页面就是一个Fragment,我们可以在fragment中实现丰富的功能.它的基本用法可以 ...
- 【原+转】创建CocoaPods私有podspec
在我的上一篇文章<iOS 手把手教你发布代码到CocoaPods>中着重介绍如何将自己的代码索引添加到公开的CocoaPods中,当你需要主动地向大众开源你的代码时需要那么做.但在现实中我 ...
- Android客户端与Eclipse服务器端的Socket通信
Server端代码 用来实现客户端socket的监听 package MyServer; import java.io.BufferedReader; import java.io.BufferedW ...
- 省市区三级联动 pickerView
效果图 概述 关于 省市区 三级联动的 pickerView,我想大多数的 iOS 开发者应该都遇到过这样的需求.在遇到这样的需求的时候,大多数人都会觉的这个很复杂,一时无从下手.其实真的没那么复杂. ...
- SqlServer数据类型
Character 字符串: 数据类型 描述 存储 char(n) 固定长度的字符串.最多 8,000 个字符. n varchar(n) 可变长度的字符串.最多 8,000 个字符. varch ...
- MS SQL 需要定期清理日志文件
前言碎语 关于对SQL SERVER 日志文件管理方面了解不多的话,可以参考我的这篇博客文章“MS SQL 日志记录管理”,不过这篇文章只是介绍对SQL SERVER日志记录的深入认知了解,并没有提出 ...
- Oracle逻辑结构(TableSpace→Segment→Extent→Block)
一.逻辑体系结构图 二.逻辑结构图组成介绍 从上表可以看出,一个数据库是由多个表空间(tablespace)组成,一个表空间又由多个段(segment)组成,一个段又由多个区(extent)组成,一个 ...
- SQL Server 2008 R2——TRUNCATE TABLE 无法截断表 该表正由 FOREIGN KEY 约束引用
=================================版权声明================================= 版权声明:原创文章 禁止转载 请通过右侧公告中的“联系邮 ...
- C#调用C/C++动态库 封送结构体,结构体数组
一. 结构体的传递 #define JNAAPI extern "C" __declspec(dllexport) // C方式导出函数 typedef struct { int ...
- 【转】去除eclipse的JS验证
第一步:去除eclipse的JS验证:将windows->preference->Java Script->Validator->Errors/Warnings->Ena ...