iOS使用NSURLConnection发送同步和异步HTTP Request
1. 同步发送
- (NSString *)sendRequestSync
{
// 初始化请求, 这里是变长的, 方便扩展
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; // 设置
[request setURL:[NSURL URLWithString:urlStr]];
[request setHTTPMethod:@"POST"];
[request setValue:host forHTTPHeaderField:@"Host"];
NSString *contentLength = [NSString stringWithFormat:@"%d", [content length]];
[request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:content]; // 发送同步请求, data就是返回的数据
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if (data == nil) {
NSLog(@"send request failed: %@", error);
return nil;
} NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"response: %@", response);
return response;
}
2.异步发送
1) 使用delegate的方式:
- (void)sendRequestAsync
{
// 初始化请求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; // 设置
[request setURL:[NSURL URLWithString:urlStr]];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; // 设置缓存策略
[request setTimeoutInterval:5.0]; // 设置超时 //...... receivedData = [[NSMutableData alloc] initData: nil]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection == nil) {
// 创建失败
return;
}
}
异步发送使用代理的方式, 需要实现以下delegate接口:
// 收到回应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"receive the response");
// 注意这里将NSURLResponse对象转换成NSHTTPURLResponse对象才能去
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog(@"allHeaderFields: %@",dictionary);
}
[receivedData setLength:];
} // 接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"get some data");
[receivedData appendData:data];
} // 数据接收完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *results = [[NSString alloc]
initWithBytes:[receivedData bytes]
length:[receivedData length]
encoding:NSUTF8StringEncoding]; NSLog(@"connectionDidFinishLoading: %@",results);
} // 返回错误
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection failed: %@", error);
}
2) iOS 5.0版本新增异步发送接口:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue*) queue
completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handlerNS_AVAILABLE(10_7, 5_0);
iOS使用NSURLConnection发送同步和异步HTTP Request的更多相关文章
- iOS GCD基础篇 - 同步、异步,并发、并行的理解
1.关于GCD - GCD全称是Grand Central Dispatch - GCD是苹果公司为多核的并行运算提出的解决方案 - GCD会自动利用更多的CPU内核(比如双核.四核) - GC ...
- IOS 调用WebService(同步和异步)
因为公司的服务全都是webservice,每次总要花费大量时间在调试服务上面,干脆就写了一个解析wsdl的项目,希望将来能用上吧.还未经过烘焙,有问题,还请高手点播点播. 下面,我拿天气服务的wsdl ...
- ios开发网络学习:一:NSURLConnection发送GET,POST请求
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...
- iOS边练边学--NSURLConnection发送HTTP请求以及NSString和NSData的相互转换
HTTP请求的常见方法 GET 所有参数拼接在URL后面,并且参数之间用&隔开 比如http://520it.com?name=123&pwd=345 传递了2个参数给服务器 name ...
- iOS上的http请求:get、post以及同步、异步
1.get: view sourceprint" class="item about" style="color:rgb(51,51,51); text-dec ...
- iOS开发中如何实现同步、异步、GET、POST等请求实操演示!
1.同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作, 2.异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然 ...
- IOS多线程知识总结/队列概念/GCD/主队列/并行队列/全局队列/主队列/串行队列/同步任务/异步任务区别(附代码)
进程:正在进行中的程序被称为进程,负责程序运行的内存分配;每一个进程都有自己独立的虚拟内存空间 线程:线程是进程中一个独立的执行路径(控制单元);一个进程中至少包含一条线程,即主线程 队列 dispa ...
- kafka7 探索生产者同步or异步发送消息
1.生产者:在发送完消息后,收到回执确认. 主要是在SimpleProducer.java中修改了发送消息的2行代码,用到了回调函数,修改如下: //发送消息 ProducerRecord<St ...
- iOS:转载:同步、异步、并行、串行的详解
理解 iOS 开发中 GCD 相关的同步(synchronization)\ 异步(asynchronization),串行(serial)\ 并行(concurrency)概念 2014年11月21 ...
随机推荐
- linux 的服务与进程管理(二)
2.linux 的服务与进程管理 [2.1]系统启动流程 简单的介绍下linux的系统启动流程,方便我们深入了解linux操作系统,对排除linux系统故障进行帮助.启动流程虽然简单但背后还有着更加复 ...
- 百度地图Api进阶教程-用户自定义数据(标记和搜索)7.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- C程序模拟实现银行家算法
C程序模拟实现银行家算法 上周又做操作系统实验,题目是用程序模拟实现银行家算法,写了半天还真有点晕,主要是因为想尽可能符合课本上的描述,所以写出来的程序就比较恶心了,好了,银行家算法就不多说了,不了解 ...
- C# 最全的系统帮助类
using System;using System.Collections;using System.Collections.Generic;using System.Configuration;us ...
- [hbase] 查询数据
获取hbase数据 说说:count 'SOCIA:T_SOCIA_ALBUM_TALK'scan 'SOCIA:T_SOCIA_ALBUM_TALK',{LIMIT=>5}get 'SOCIA ...
- Change Data template dynamically
1. Attached Property bound to task state. Any change will dynamically set data template.2. Visual St ...
- String直接赋值和使用new的区别
String str1 = "ABC"; String str2 = new String("ABC"); String str1 = “ABC”;可能创建一个 ...
- 取消excel 工作保护 密码的宏
Option Explicit Public Sub AllInternalPasswords() ' Breaks worksheet and workbook structure password ...
- AngularJS $http模块POST数据,后台接受不到
1.问题: 后端接收不到AngularJs中$http.post发送的数据,总是显示为null 示例代码: $http.post(/admin/KeyValue/GetListByPage, { pa ...
- Radix-64编码简介
本文介绍Radix-64编码,PGP和S/MIME均使用了Radix-64编码技术,rfc4880的Chap 6有关于Radix-64的详细描述. Radix-64编码基于Base64编码技术,由两部 ...