URLRequest 的一个实例
- // Create the request.
- //所构建的NSURLRequest具有一个依赖于缓存响应的特定策略,cachePolicy取得策略,timeoutInterval取得超时值
- NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"
http://www.weather.com.cn/data/cityinfo/101110101.html
"] - cachePolicy:NSURLRequestUseProtocolCachePolicy
- timeoutInterval:60.0];
- // create the connection with the request
- // and start loading the data
- NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
- if (theConnection) {
- // Create the NSMutableData to hold the received data.
- // receivedData is an instance variable declared elsewhere.
- receivedData = [[NSMutableData data] retain];
- } else {
- // Inform the user that the connection failed.
- }
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
redata=(NSMutableData*)data;
NSString *tmp=[[NSStringalloc] initWithData:redata encoding:NSUTF8StringEncoding];
NSLog(@"%@",tmp);
// 返回一个JSON对象 使用jsonkit对数据进行转化
NSDictionary *json=[redataobjectFromJSONData];
//对字典数据进行操作
}
- (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
- // 初始化请求
- NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
- // 设置URL
- [request setURL:[NSURL URLWithString:urlStr]];
- // 设置HTTP方法
- [request setHTTPMethod:@"GET"];
- // 发 送同步请求, 这里得returnData就是返回得数据了
- NSData *returnData = [NSURLConnection sendSynchronousRequest:request
- returningResponse:nil error:nil];
- // 释放对象
- [request release];
- NSString *url = [NSString stringWithFormat:@"http://localhost/chat/messages.php?past=%ld&t=%ld",
- lastId, time(0) ];
- NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
- [request setURL:[NSURL URLWithString:url]];
- [request setHTTPMethod:@"GET"];
- NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
- if (conn)
- {
- receivedData = [[NSMutableData data] retain];
- }
- else
- {
- }
- - (void)timerCallback {
- //[timer release];
- [self getNewMessages];
- }
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- {
- [receivedData setLength:0];
- }
- - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- {
- [receivedData appendData:data];
- 对数据进行操作
- }
- - (void)connectionDidFinishLoading:(NSURLConnection *)connection
- {
- }