网络请求数据 get请求方式   post请求 协议异步连接服务器 block异步连接服务器

网络请求三部

  1. 创建一个请求(添加接口,对接口进行解码,)
  2. 设定请求方式(将接口转为NSURL,设置请求[请求地址, 缓存策略, 超时时间],设置请求方式)
  3. 连接服务器([同步连接,异步连接]代理连接,block连接)
#import "MainViewController.h"
@interface MainViewController ()
@property (retain, nonatomic) IBOutlet UIImageView *ImageWiew;
//get请求方法
- (IBAction)getConnection:(id)sender;
//post请求方法
- (IBAction)postConnection:(id)sender;
//协议方式实现异步连接服务器
- (IBAction)buttonDelegate:(id)sender;
//block异步连接服务器
- (IBAction)buttonBlock:(id)sender;
//一个可变的数据属性,用于拼接每次从服务器请求的小数据块
@property (nonatomic , retain)NSMutableData *receiveData;
@end
@implementation MainViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
//        //初始化方法
//        self.receiveData = [NSMutableData data];
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)dealloc {
    [_ImageWiew release];
    [super dealloc];
}
- (IBAction)getConnection:(id)sender {
    //实现网络请求_get请求方式
    //注意错误:地址不能有错,网络不能断
    NSString *str = @"http://cdn.gq.com.tw.s3-ap-northeast-1.amazonaws.com/userfiles/images_A1/6954/2011100658141857.jpg";
    //要请求的图片地址
    
    
    //网络请求三步
    //1.创建一个请求,设定请求方式(GET/POST)
    
    NSURL *url = [NSURL URLWithString:str];
    //参数1:请求的地址信息(需要转成URL类型)
    //参数2;请求的缓存策略(缓存策略,服务器指定的)
    //参数3:设置超时的时间
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    //设置请求方式
    request.HTTPMethod = @"GET";
    //2.连接服务器,发送请求
    //连接服务器两种不同的方式: 一,同步连接 二,异步连接
    
    //同步连接服务器
    //参数1:要发送的网络请求
    //参数2:服务器对这次请求的响应信息
    NSURLResponse *response = nil;
    NSError *error = nil;
    //这个方法会卡住整个应用程序,直到完整的数据被请求下来之后才继续执行
   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    //把请求下来的数据(data)转换成图片
    UIImage *image = [UIImage imageWithData:data];
    self.ImageWiew.image = image;
    
    NSLog(@"服务器响应信息:%@", response);
    NSLog(@"错误信息:%@", error);
  
}
- (IBAction)postConnection:(id)sender {
    //创建一个post请求
    
    //1.创建一个请求,设定pos
    NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    
    //设置请求方式
    request.HTTPMethod = @"POST";
    //post请求,需要带一个数据;
    NSString *strBody = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    //把一段字符串转换为NSData类型,方便发送;
    request.HTTPBody = [strBody dataUsingEncoding:NSUTF8StringEncoding];
    //2.连接服务器
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    //转为字符串检测是什么类型的数据
    NSString *resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"结果:%@",resultStr);
    
    NSLog(@"服务器响应信息%@", response);
    
    
    
    
}
- (IBAction)buttonDelegate:(id)sender {
    //基于协议的异步请求
    
    //创建一个请求
    NSString *string = @"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=0&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a";
    //带有特殊字符的汉子(汉字,|,..)需要提前转码
    NSString *newStr = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:newStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"get";
    
    //2.连接服务器
    
    //创建一个网络连接对象
    //设置网络连接的代理(这个代理有三个必须要实现的方法)(记得加代理<NSURLConnectionDataDelegate>)
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  
    
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //接收到服务器响应信息的时候(三次握手)
    NSLog(@"服务器响应");
    self.receiveData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //接收到服务器发送的数据
    NSLog(@"服务器发送数据");
    //每次接收到数据的时候都把数据拼接起来
    [self.receiveData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //接收数据完成
    NSLog(@"数据接收完毕");
    //数据请求完毕,对data进行解析
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",dic);
}
- (IBAction)buttonBlock:(id)sender {
    //1.创建请求
    NSString *str = @"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=0&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a";
    NSString *newStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:newStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"get";
    
    //2.连接服务器
    //参数1:请求  参数2:请求结束后,返回到哪个线程继续执行任务  参数3:请求结束,执行block中的代码
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //data是完整的请求完毕的数据
        if (data != nil) {  //对data的一个判断...
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dic);
        }
    }];
    
    
}
@end
时间: 2024-08-03 03:12:01

网络请求数据 get请求方式   post请求 协议异步连接服务器 block异步连接服务器的相关文章

HttpClient的Post请求数据

最近在项目中需要添加Post请求数据,以前的Get请求是使用JDK自带的URLConnection.在项目组人员的推荐下,开始使用HttpClient. HttpClient简介: HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包, 并且它支持HTTP协议最新的版本和建议.HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus 和HTMLUn

Angular 请求数据

Angular 请求数据 get post 以及 jsonp 请求数据 引入 HttpModule .JsonpModule 普通的 HTTP 调用并不需要用到 JsonpModule,不过稍后我们就会延演示对 JSONP 的支持,所以现在就加载它,免得再回来浪费时间. 引入模块 注意:JSONP 在4版本以后已经被弃用了... import { HttpClientJsonpModule, HttpClientModule } from '@angular/common/http'; 在 im

311 同步异步概述,Ajax 异步请求

09.Ajax异步请求.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script type="text/javascript"> // 1.创建ajax对象 var xh

Android网络之数据解析----使用Google Gson解析Json数据

[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4063452.html 联系方式:[email protected] [正文] 文章回顾: Android网络之数据解析----SAX方式解析XML数据 一.Json数据的介绍                                                             

iOS进阶学习-网络之数据请求

注:文中出现的网站只做用例子,所以有些已经失效的网站,具体URL大家可以自己上网搜索相关资源. 一.HTTP和HTTPS协议 1.URL: URL全称是Uniform Resource Locator(统一资源定位符)通过1个URL,能找到互联网上唯一的1个资源 URL就是资源的地址.位置,互联网上的每个资源都有一个唯一的URL URL的基本格式=协议://主机地址/路径 http://www.cnblogs.com/soley 协议:不同的协议,代表着不同的资源查找方式,资源传输方式 主机地址

常见从网络上请求数据流程

GET请求与POST请求区别 1.GET请求的接口会包含参数部分,参数会作为网址的一部分,服务器地址与参数之间通过?来间隔.POST请求会将服务器地址与参数分开,请求接口中只有服务器地址,而参数会作为请求体的一部分,提交给后台服务器 2.GET请求参数会出现在接口中,不安全,而POST请求相对安全 3.虽然GET请求与POST请求都可以用来请求与提交数据,POST多用于向后台提交数据,GET多用于从后台请求数据 4.同步与异步的区别: 同步连接:主线程去请求数据,当数据请求完毕之前,其它操作一律

iOS网络之数据请求

1. HTTP和HTTPS协议 1> URL URL全称是Uniform Resource Locator(统一资源定位符)通过1个URL,能找到互联网上唯一的1个资源 URL就是资源的地址.位置,互联网上的每个资源都有一个唯一的URL URL的基本格式=协议://主机地址/路径 http://www.cnblogs.com/gfxxbk/ 协议:不同的协议,代表着不同的资源查找方式,资源传输方式 主机地址:存放资源的主机的IP地址(域名) 路径:资源在主机中的位置 2> HTTP协议的概念

【黑马Android】(05)短信/查询和添加/内容观察者使用/子线程网络图片查看器和Handler消息处理器/html查看器/使用HttpURLConnection采用Post方式请求数据/开源项目

备份短信和添加短信 操作系统短信的uri: content://sms/ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.itheima28.backupsms" android:versionCode="1

ios之NSURLConnection网络请求数据/GET与POST方法

目前可能只是单纯的贴上了一些demo的代码,但是这些代码都是请求数据应该是最基础的使用方法吧,在项目的实际开发中可能用到系统的会非常少,一般都是采用别人非常成熟的第三方开源库来实现数据请求,目前常用的第三方网络请求主要是以下几个:<h3 style="margin: 18px 0px; padding: 0px 0px 5px; border: 0px; outline: 0px; font-size: 22px; vertical-align: baseline; color: rgb(