[iOS 多线程 & 网络 - 2.0] - 发送接收 服务器信息
GET
GET的语义是获取指定URL的资源
将数据按照variable=value的形式,添加到action所指向的URL后面,并且两者使用"?"连接,各变量之间使用"&"连接
貌似不安全,因为在传输过程中,数据被放在请求的URL中

POST的语义是向指定URL的资源添加数据
将数据放在数据体中,按照变量和值相对应的方式,传递到action所指向URL
所有数据对用户来说不可见
可以传输大量数据,上传文件只能使用Post

默认为GET请求
对于POST请求,需要创建请求的数据体
利用URLConnection发送网络请求(建立连接)
获得结果
NSURLConnection提供了两个静态方法可以直接以同步或异步的方式向服务器发送网络请求
同步请求:
sendSynchronousRequest:returningResponse:error:
异步请求:
sendAsynchronousRequest:queue: completionHandler:
服务器开始返回数据,准备工作
(void)connection:didReceiveResponse:
收到服务器返回的数据,本方法会被调用多次
- (void)connection:didReceiveData:
数据接收完毕,做数据的最后处理
(void)connectionDidFinishLoading:
网络连接错误
- (void)connection:didFailWithError:

().使用同步方法发送get请求(不常用)
/** 发送get消息 */
- (void) testGet {
NSString *requestStr = [NSString stringWithFormat:@"http://192.168.0.21:8080/MyTestServer/login?user=%@&password=%@", self.userField.text, self.passwordField.text]; NSURL *url = [NSURL URLWithString:requestStr]; // 默认就是get请求
NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 使用同步方法发送请求
[self sendSynRequest:request];
} /** 同步发送请求 */
- (void) sendSynRequest:(NSURLRequest *) request {
// 同步发送信息
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; [self dealWithResponseData:data];
} /** 处理返回数据 */
- (void) dealWithResponseData:(NSData *) data {
// 解析数据
if (data) { // 得到返回数据
// 解除屏幕锁
[MBProgressHUD hideHUD]; // 解析json数据
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; // 处理返回的数据
NSString *result = dict[@"success"];
if (result) {
[MBProgressHUD showSuccess:result];
} else {
result = dict[@"error"];
if (result) {
[MBProgressHUD showError:result];
}
}
} else {
[MBProgressHUD showError:@"网络繁忙,请稍后再试~"];
}
}
/** 异步发送请求 */
- (void) sendAsynRequest:(NSURLRequest *) request {
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { [self dealWithResponseData:data];
}];
}
@interface ViewController () <NSURLConnectionDataDelegate>
/** 使用start & 代理发送、处理异步请求 */
- (void) sendAsynRequestWithDelegate:(NSURLRequest *) request {
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
#pragma mark - NSURLConnectionDataDelegate 代理方法
/** 收到服务器回应 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiveResponse");
self.data = [NSMutableData data];
} /** 接收到的数据,会调用多次,数据被分割接收 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"didReceiveData");
[self.data appendData:data];
} /** 接收数据完毕 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
[self dealWithResponseData:self.data];
}
#pragma mark - post
- (void) testPost {
NSString *requestStr = [NSString stringWithFormat:@"http://192.168.0.21:8080/MyTestServer/login"];
NSURL *url = [NSURL URLWithString:requestStr]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.timeoutInterval = ; // 设置为post方式请求
request.HTTPMethod = @"POST"; // 设置请求头
[request setValue:@"ios" forHTTPHeaderField:@"User-Agent"]; // 设置请求体
NSString *param = [NSString stringWithFormat:@"user=%@&password=%@", self.userField.text, self.passwordField.text];
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding]; // 发送请求
// 使用主线程来处理UI刷新
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
[self dealWithResponseData:data];
}]; }
// 使用可变request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 设置请求超时时间
request.timeoutInterval = ;
NSString *requestStr = [NSString stringWithFormat:@"http://192.168.0.21:8080/MyTestServer/login?user=%@&password=%@", self.userField.text, self.passwordField.text];
// 由于url不能传送中文,所以需要转码
requestStr = [requestStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[iOS 多线程 & 网络 - 2.0] - 发送接收 服务器信息的更多相关文章
- [iOS 多线程 & 网络 - 3.0] - 在线动画Demo
A.需求 所有数据都从服务器下载 动画列表包含:图片.动画名标题.时长副标题 点击打开动画观看 code source: https://github.com/hellovoidworld/Vid ...
- iOS多线程与网络开发之发送接收server信息
郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. (1).使用同步方法发送get请求(不经常使用) 2 /** 发送get消息 */ 3 - (void) testGet { 4 NSString *r ...
- [iOS 多线程 & 网络 - 1.0] - 多线程概述
A.进程 什么是进程进程是指在系统中正在运行的一个应用程序 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内 比如同时打开QQ.Xcode,系统就会分别启动2个进程 通过"活 ...
- [iOS 多线程 & 网络 - 4.0] - AFN框架简单使用
A.AFN基本知识 1.概念 AFNetworking 是对NSURLConnection的封装 运行效率没有ASI高(因为ASI基于CFNetwork),但是使用简单 AFN支持ARC B. ...
- [iOS 多线程 & 网络 - 2.4] - 大文件下载 (边下边写/暂停恢复下载/压缩解压zip/多线程下载)
A.需求 边下边写入硬盘 显示下载进度 暂停/恢复 下载 解压文件 多线程下载 B.基本知识 1.小文件下载 如果文件比较小,下载方式会比较多直接用NSData的+ (id)dataWithCon ...
- [iOS 多线程 & 网络 - 2.10] - ASI框架下载文件
A.ASI框架中的下载 1.实现步骤 在实际的开发中如果要使用asi框架来下载服务器上的文件,只需要执行下面简单的几个步骤即可. (1)创建请求对象:(2)设置下载文件保存的路径:(3)发送下载文件的 ...
- [iOS 多线程 & 网络 - 2.9] - ASI框架
A.ASI基本知识 1.ASI简单介绍 ASI:全称是ASIHTTPRequest,外号“HTTP终结者”,功能十分强大. ASI的实现基于底层的CFNetwork框架,因此运行效率很高. ASI的g ...
- [iOS 多线程 & 网络 - 2.7] - NSURLCache
A.基本知识 1.为什么需要缓存? 有时候一个url会请求多次,得到的内容确实一样的 2.缓存的概念 3.缓存数据的过程 当服务器返回数据时,需要做以下步骤(1)使用服务器的数 ...
- [iOS 多线程 & 网络 - 2.6] - 使用POST上传JSON数据 & 多值参数
A.上传JSON 1.思路: 必须使用POST方法才能上传大量JSON数据 设置请求头:设置Content-Type 设置请求体,JSON实际相当于字典,可以用NSDictionary NSJSONS ...
随机推荐
- Android查询:模拟键盘鼠标事件(adb shell 实现)
1. 发送键盘事件: 命令格式1:adb shell input keyevent “value” 其中value以及对应的key code如下表所列: KeyEvent Value KEYCODE ...
- .frm文件
http://www.cnblogs.com/jiangxu67/p/4755097.html MySQL]frm文件解析 MySQL 协议字节序 关于传输整数小大端的实现 http://hamilt ...
- BZOJ1272: [BeiJingWc2008]Gate Of Babylon
题解: 多重集合的组合数?还是0-m?有些元素有个数限制? 多重集合的组合数可以插板法,0-m直接利用组合数的公式一遍求出来,个数限制注意到只有15个,那我们就暴力容斥了 AC了真舒畅.. 注意开lo ...
- hdu 4635 Strongly connected(强连通)
考强连通缩点,算模板题吧,比赛的时候又想多了,大概是不自信吧,才开始认真搞图论,把题目想复杂了. 题意就是给你任意图,保证是simple directed graph,问最多加多少条边能使图仍然是si ...
- angular js 指令的数据传递 及作用域数据绑定
<div my-directive my-url="http://google.com" my-link-text="Click me to go to Googl ...
- Java [leetcode 6] ZigZag Conversion
问题描述: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows ...
- jquery仿邮箱文本输入框自动加载邮箱后缀
在像百度这样的网站注册时,你会看到输入邮箱会出现自动给用户输入补全主流邮箱.这种对于增加用户体验的小例子已司空见惯.正好看到人家写的这种js功能.还挺不错,使用起来很方便,几乎不用写神呢代码.&quo ...
- 30种oracle常见的等待事件说明
1Buffer busy waits从本质上讲,这个等待事件的产生仅说明了一个会话在等待一个Buffer(数据块),但是导致这个现象的原因却有很多种.常见的两种是: 当一个会话视图修改一个数据块,但这 ...
- windows主线程等待子线程退出卡死问题
在windows下调用_beginthread创建子线程并获得子线程id(函数返回值),如果子线程很快退出,在主线程中调用WaitForSingleObject等待该线程id退出,会导致主线程卡死.需 ...
- [转] AE之分级颜色专题图渲染
原文 AE之分级颜色专题图渲染 参考代码1 private void 分级渲染ToolStripMenuItem_Click(object sender, EventArgs e) { //值分级 I ...