`
mmdev
  • 浏览: 12923769 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

URLRequest 的一个实例

 
阅读更多

URLRequest 的一个实例

  1. //Createtherequest.
  2. //所构建的NSURLRequest具有一个依赖于缓存响应的特定策略,cachePolicy取得策略,timeoutInterval取得超时值
  3. NSURLRequest*theRequest=[NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://www.apple.com/"]
  4. cachePolicy:NSURLRequestUseProtocolCachePolicy
  5. timeoutInterval:60.0];
  6. //createtheconnectionwiththerequest
  7. //andstartloadingthedata
  8. NSURLConnection*theConnection=[[NSURLConnectionalloc]initWithRequest:theRequestdelegate:self];
  9. if(theConnection){
  10. //CreatetheNSMutableDatatoholdthereceiveddata.
  11. //receivedDataisaninstancevariabledeclaredelsewhere.
  12. receivedData=[[NSMutableDatadata]retain];
  13. }else{
  14. //Informtheuserthattheconnectionfailed.
  15. }
from:http://blog.csdn.net/bl1988530/article/details/6590099

其中:
NSURLRequest默认的cache policy是NSURLRequestUseProtocolCachePolicy, 是最能保持一致性的协议。
NSURLRequestReloadIgnoringCacheData忽略缓存直接从原始地址下载
NSURLRequestReturnCacheDataElseLoad只有在cache中不存在data时才从原始地址下载
NSURLRequestReturnCacheDataDontLoad允许app确定是否要返回cache数据,如果使用这种协议当本地不存在response的时候,创建NSURLConnection or NSURLDownload实例时将会马上返回nil;这类似于离线模式,没有建立网络连接;

你只需要实现以下delegate方法来处理数据响应

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

NSURLConnect还提供了一个方便的类方法(class method) : sendSynchronousRequest:returningResponse:error:可用来同步地加载一个URL请求

+ (NSData *)sendSynchronousRequest: (NSURLRequest *)request returningResponse: (NSURLResponse **)response error: (NSError **)error

  • request 要装载的URL请求. 这个request 对象 作为初始化进程的一部分,被深度复制(deep-copied). 在这个方法返回之后, 再修改request, 将不会影响用在装载的过程中的request
  • reponse 输出参数, 由服务器返回的URL响应
  • error 输出参数, 如果在处理请求的过程中发生错误,就会使用. 无错误,就为NULL


一个实现异步get请求的例子:
  1. NSString*url=[NSStringstringWithFormat:@"http://localhost/chat/messages.php?past=%ld&t=%ld",
  2. lastId,time(0)];
  3. NSMutableURLRequest*request=[[[NSMutableURLRequestalloc]init]autorelease];
  4. [requestsetURL:[NSURLURLWithString:url]];
  5. [requestsetHTTPMethod:@"GET"];
  6. NSURLConnection*conn=[[NSURLConnectionalloc]initWithRequest:requestdelegate:self];
  7. if(conn)
  8. {
  9. receivedData=[[NSMutableDatadata]retain];
  10. }
  11. else
  12. {
  13. }
  14. -(void)timerCallback{
  15. //[timerrelease];
  16. [selfgetNewMessages];
  17. }
  18. -(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)response
  19. {
  20. [receivedDatasetLength:0];
  21. }
  22. -(void)connection:(NSURLConnection*)connectiondidReceiveData:(NSData*)data
  23. {
  24. [receivedDataappendData:data];
  25. }
  26. -(void)connectionDidFinishLoading:(NSURLConnection*)connection
  27. {
  28. if(chatParser)
  29. [chatParserrelease];
  30. if(messages==nil)
  31. messages=[[NSMutableArrayalloc]init];
  32. chatParser=[[NSXMLParseralloc]initWithData:receivedData];
  33. [chatParsersetDelegate:self];//setthedelegate
  34. [chatParserparse];//startparse
  35. [receivedDatarelease];
  36. [messageListreloadData];
  37. NSInvocation*invocation=[NSInvocationinvocationWithMethodSignature:
  38. [selfmethodSignatureForSelector:@selector(timerCallback)]];
  39. [invocationsetTarget:self];
  40. [invocationsetSelector:@selector(timerCallback)];
  41. //timer=[NSTimerscheduledTimerWithTimeInterval:5.0invocation:invocationrepeats:NO];
  42. [NSTimerscheduledTimerWithTimeInterval:5.0invocation:invocationrepeats:NO];//ifsetyes,thenvery5secondsupdatathetable
  43. }



一个实现同步Get请求的例子:
  1. //初始化请求
  2. NSMutableURLRequest*request=[[NSMutableURLRequestalloc]init];
  3. //设置URL
  4. [requestsetURL:[NSURLURLWithString:urlStr]];
  5. //设置HTTP方法
  6. [requestsetHTTPMethod:@"GET"];
  7. //发送同步请求,这里得returnData就是返回得数据了
  8. NSData*returnData=[NSURLConnectionsendSynchronousRequest:request
  9. returningResponse:nilerror:nil];
  10. //释放对象
  11. [requestrelease];
from:http://blog.csdn.net/bl1988530/article/details/6590099
分享到:
评论

相关推荐

    AS3 中使用 URLRequest 和 URLLoader 与服务器交互

    AS3 中使用 URLRequest 和 URLLoader 与服务器交互AS3 中使用 URLRequest 和 URLLoader 与服务器交互AS3 中使用 URLRequest 和 URLLoader 与服务器交互AS3 中使用 URLRequest 和 URLLoader 与服务器交互AS3 中使用 ...

    AS3中使用URLRequest和URLLoader 与服务器交互

    AS3 中使用 URLRequest 和 URLLoader 与服务器交互

    flex通过URL获取request参数

    通过网页地址URL的参数传递。 例如:http://localhost:8080/text.mxml?myName=good&myValue=goods 在mxml里面获取到good同goods

    CurlDSL:CurlDSL将cURL命令转换为URLRequest对象

    它也不是Swift代码生成器,而是一个简单的解释器,它在运行时解析并解释您的cURL命令。 该项目的灵感来自 。 CurlDSL目前仅支持HTTP和HTTPS。要求Swift 5.1或以上iOS 13或以上macOS 10.15或更高版本tvOS 13或以上...

    Alley:基本的“ URLSessionDataTask”微包装器,用于与HTTP(S)Web服务进行通信,并具有内置的自动请求重试功能

    第一个极为重要,因为数据是您执行此操作的根本原因。 因此,Alley的主要特征是针对预定义条件的自动请求重试。用法您将已经可以使用一些URLSession实例。 然后代替这个: let urlRequest = URLRequest ( ... )...

    ios 网络架构

    ios网络层架构 代码很简单, 接口根据参数调用urlStringWithPath:useHttps:通过BaseURL和URLPath拼装出完整的URL, 然后用这个URL和其他参数生成一个URLRequest, 然后调用setCommonRequestHeaderForRequest:设置公用...

    As3访问http和webService的类,HttpRequest

    var Request:URLRequest = new URLRequest(url); Request.method=method; Request.data = vars; trace(vars); loader = new URLLoader(Request); callBack = _returnMethod; loader....

    ActionScript 3.0 与网络通信

    一是若只是发送不需要返回数据,则可以使用sendToURL()方法来实现,其用法格式如下:sendToURL(req:URLRequest) 二是既需要发送数据,也需要返回数据,则使用Loader对象的load()方法来实现。 通常的数据发送需要...

    AS3读取XML

    简单的读取XML:加载部分var myXML:XML = new XML(); var XML_URL:String = "dat.xml";...var myXMLURL:URLRequest = new URLRequest(XML_URL); var myLoader:URLLoader = new URLLoader(myXMLURL);

    Flex 编程技巧

    2. 复制一个 ArrayCollection 1. //dummy solution( well, it works ) 2. var bar:ArrayCollection = new ArrayCollection(); 3. for each ( var i:Object in ac ){ 4. bar.addItem( i ); 5. } 6. // fantastic ! //...

    NukeUI:SwiftUI 的延迟图像加载

    用户界面 ... 第一个稳定版本即将推出。 懒人图片 该视图使用源实例化,其中源可以是String 、 URL 、 URLRequest或 。 struct ContainerView : View { var body: some View { LazyImage ( source :

    PHP利用Flash文件上传图片(附FLA源文件).rar

     upload.fla 文件中第一帧第代码第14行:urlRequest.url = "http://localhost/phpFlash/upload.php";  此路径改为您的本地环境配置路径,注意,路径一定要以http开头。  2.上传目录  upload.php 文件中第二行...

    Flash结合PHP实现文件上传功能.rar

     upload.fla 文件中第一帧第代码第14行:urlRequest.url = "http://localhost/phpFlash/upload.php";  此路径改为您的本地环境配置路径,注意,路径一定要以http开头。    2.上传目录  upload.php 文件中第...

    NetworkEye:NetworkEye是一个网络监视器,自动捕获各种请求发送的请求和响应信息

    网络眼 NetworkEye是一个网络监视器,自动捕获各种请求发送的请求和响应信息家庭该库源自项目,该项目可以使用一行代码自动显示Log,Crash,Network,ANR,Leak,CPU,RAM,FPS,NetFlow,Folder等。 就像上帝睁开...

    iOS-Hyperspace:一个非常轻量级的URLSession包装器,使使用API​​变得轻而易举

    基本上,这是利用HTTP中的定义围绕URLRequest进行的一个瘦包装。 TransportService-使用TransportSession (默认为URLSession )执行URLRequests 。 处理原始HTTP和Data 。 BackendService-使用Transp

    经典频谱文件

    import flash.net.URLRequest; import flash.utils.ByteArray; import flash.text.TextField; public class SoundMixer_computeSpectrum extends Sprite { public function SoundMixer_computeSpectrum() { ...

    flash as3 加载外部mp3

    //文本提示:动态文本框 ts_txt //"非你莫属.mp3 和fla在同一目录,如果不在同一目录要使用完整的绝对路径。 var s:Sound = new Sound() var req:URLRequest=new URLRequest("非你莫属.mp3")

    Flex 常用实现小功能的语句

    我做flex项目时收集的,与大家共享,...(如:页面重载: navigateToURL(new URLRequest("javascript:location.reload();"),"_self") 关闭浏览器:navigateToURL(new URLRequest("javascript:window.close()"),"_self");)

    CS6打开歌词同步频谱播放器源码

    import flash.net.URLRequest; import flash.ui.ContextMenu; import flash.ui.ContextMenuItem; //===============// public class Main extends Sprite { private var xmlLoader:DataLoader; private ...

Global site tag (gtag.js) - Google Analytics