http请求

来源:互联网 发布:数据恢复价格 编辑:程序博客网 时间:2024/05/02 04:56

转载:http://blog.csdn.net/nicktang/article/details/6870454


网络编程是iOS开发的重要一环,重要性就不多讲了,下面的代码也比较简单,我在这里也不多解释了。

 

 

 

NSString *url = 。。。//这里打包URL 
 NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
            timeoutInterval:K_IN_TIME_OUT];//K_IN_TIME_OUT是以秒为单位的过期时间,30即可
 
 NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
 if (theConnection) {
  //NSLog(@"Connect successfully.");
 } else {
  //NSLog(@"Fail to connect ");
 }
 [url release];

 

 

#pragma mark -
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
 NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
 int responseStatusCode = [httpResponse statusCode];

....

//请求成功返回,responseStatusCode 是返回代码。
}

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

//由于http请求的数据是TCP的方式,分段返回的,所以这个函数可能会多次被调用。receivedData 是NSMutableData *
 if (nil == receivedData ) {
  receivedData = [[NSMutableData alloc]initWithData:data];
 }
 else {
  [receivedData appendData:data];
 }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

//请求完成,得到了返回数据在receivedData中。
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//http请求出错时被调用。
}

 


 

注意上面的代码中的内存管理问题。

原创粉丝点击