iOS中的请求(GET请求,POST请求,同步请求,异步请求)

1.用到的一些第三方

PostTableViewController.m
#import "PostTableViewController.h"

@interface PostTableViewController ()

@property(nonatomic,retain) NSArray *dataArr;

@end

@implementation PostTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)handleBtnT:(id)sender {
    //1.创建网址字符串对象
    NSString *str = [NSString stringWithFormat:@"http://api.tudou.com/v3/gw"];
    //2.创建NSURL对象
    NSURL *url = [NSURL URLWithString:str];
    //3.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //3.1创建参数字符串
    NSString *parmStr = [NSString stringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"];
    //3.2设置请求体(提交的内容)
    NSData *data = [parmStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    //3.3设置请求方式
    [request setHTTPMethod:@"POST"];

    //4.创建连接
    //同步
    NSData *dataNS = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    [self parsingJSON:dataNS];

}
//解析

- (void)parsingJSON:(NSData *)data{

    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
   // self.dataArr = dic[@"results"];
    NSLog(@"%@",dic);

//    self.descStr.text = dataArr[0][@"dic"];
//    self.actionStr.text = dataArr[0][@"actionStr"];
//    self.categoriesStr.text = dataArr[0][@"categoriesStr"];

   // NSLog(@"%@",dic[@"results"][0][@"dic"]);
    //[self.tableView reloadData];
}

- (IBAction)handleBtnY:(id)sender {
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];

    cell.textLabel.text = self.dataArr[0][@"dic"];
    NSLog(@"%@",self.dataArr[0][@"dic"]);
    return cell;
}

- (void)dealloc
{
    self.dataArr = nil;
    [super dealloc];
}

@end
GetTableViewController.m
#import "GetTableViewController.h"
#import "Business.h"
#import "BusinessCell.h"
@interface GetTableViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, retain) NSMutableArray *dataSourcse;// 存储所有用户数据

@property (nonatomic, retain) NSMutableData *data; //存储数据
@property (nonatomic, retain) NSURLConnection *connection; //存储连接对象
@end

@implementation GetTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableArray *)dataSourcse{
    if (!_dataSourcse) {
        self.dataSourcse = [NSMutableArray arrayWithCapacity:1];
    }
    return [[_dataSourcse retain] autorelease];
}

//同步
- (IBAction)handleBtnT:(id)sender {

    //1.创建网址字符串对象
    NSString *urlStr = [NSString stringWithFormat:@"http://api.map.baidu.com/place/v2/search?query=%@&region=%@&output=json&ak=6E823f587c95f0148c19993539b99295",@"大保健",@"郑州"];
    //2.如果字符串中出现中文需要URLEncode
    NSString *newURLStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //3.创建NSURL对象
    NSURL *url = [NSURL URLWithString:newURLStr];
    //4.创建请求对象(NSURLRequest)
    NSURLRequest *reques = [NSURLRequest requestWithURL:url];

    //同步请求
    //5.建立连接
    NSURLResponse *response = nil; // 存储服务器响应信息
    NSError *error = nil; // 存储请求失败信息
    NSData *data = [NSURLConnection sendSynchronousRequest:reques returningResponse:&response error:&error];
    //解析
    [self parsingJSON:data];
}
//异步连接
- (IBAction)handleBtnY:(id)sender {
    //1.创建网址字符串对象
    NSString *urlStr = [NSString stringWithFormat:@"http://api.map.baidu.com/place/v2/search?query=%@&region=%@&output=json&ak=6E823f587c95f0148c19993539b99295",@"大保健",@"郑州"];
    //2.如果字符串中出现中文需要URLEncode
    NSString *newURLStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //3.创建NSURL对象
    NSURL *url = [NSURL URLWithString:newURLStr];
    //4.创建请求对象(NSURLRequest)
    NSURLRequest *reques = [NSURLRequest requestWithURL:url];

    //异步连接
    //1.Block 方式
/*
    [NSURLConnection sendAsynchronousRequest:reques queue:[NSOperationQueue  mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //解析
        [self parsingJSON:data];
    }];
*/
    //2.协议和代理
   self.connection = [NSURLConnection connectionWithRequest:reques delegate:self];

}
//解析
- (void)parsingJSON:(NSData *)data
{
    //清除数组中之前的数据
    [self.dataSourcse removeAllObjects];
    //6.解析
    //此时使用可变字典来接受 , 一方面,解析之后获得是可变的容器,另一方面,得到的数据的最外层是字典,因此,使用可变字典来接受数据.
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    // NSLog(@"%@",dic);

    //获取字典中的小数组
    NSArray *dataArr = dic[@"results"];
    NSLog(@"%@",dataArr);
    //将小数组中字典对象转化为 Business 类型的对象
    for (NSDictionary *dic in dataArr) {
        Business *business = [[Business alloc] init];
        [business setValuesForKeysWithDictionary:dic];
        //添加到数组
        [self.dataSourcse addObject:business];
        [business release];
    }

    //数据解析完毕,刷新界面
    [self.tableView reloadData];

}

/**
 *  同步链接,异步链接之间的区别
    1.同步连接由主线程完成网络的请求任务,在数据请求完毕之前,所有的用户交互无处理,会造成程序卡顿,影响用户体验.
    2.异步链接,系统默认开辟子线程完成网络请求的任务,主线程依旧处理用户交互,因此,用户体验较好.操作流畅.以空间换时间.

 */

#pragma mark - NSURLConnectionDataDelegate
//当收到服务器响应时触发
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //当收到服务器响应时,开辟空间
    self.data = [NSMutableData data];
}
//当收到服务器传输的数据时
//当传输的数据比较大时,服务器并不会径所有的数据全部传输过来,可能每次传输一部分,每一次传输都会触发该方法.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
   //当收到数据时,拼接数据
    [self.data appendData:data];
}
//当接受服务器传输的数据结束时
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    //解析
    [self parsingJSON:self.data];
}
//当请求失败时
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"失败");

}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.dataSourcse.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BusinessCell *cell = [tableView dequeueReusableCellWithIdentifier:@"resuse" forIndexPath:indexPath];
    //Cell 为自身控件赋值
    cell.business = self.dataSourcse[indexPath.row];

    return cell;
}

- (void)viewWillDisappear:(BOOL)animated{
    //当将要离开该界面,去其他界面时,终止连接
    [self.connection cancel]; // 取消网络连接
}

- (void)dealloc{
    self.data = nil;
    self.dataSourcse = nil;
    self.connection = nil;
    [super dealloc];
}
@end
Business.h

#import <Foundation/Foundation.h>

@interface Business : NSObject
@property (nonatomic, copy) NSString *name; //存储商户名字
@property (nonatomic, copy) NSString *address; //存储商户地址
@property (nonatomic, copy) NSString *telephone; // 存储商户电话
@property (nonatomic, copy) NSString *business_id;// 存储商户id
@end

Business.m

#import "Business.h"
@implementation Business
//当使用KVC进行赋值时,如果使用赋值的字典中的键值对不能使用完(business)这个类 属性的个数, 少于 键值对的个数  --- 字典中的某些键值对找不到对应得属性来完成属性,此时需要实现下面的方法来处理匹配不到的情况
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    if ([key isEqualToString:@"uid"]) {
        self.business_id = value;
        NSLog(@"---- %@",self.business_id);
    }
}
- (void)dealloc{
    self.name = nil;
    self.address = nil;
    self.telephone = nil;

    [super dealloc];
}
@end
BusinessCell.h

#import <UIKit/UIKit.h>
@class Business;
@interface BusinessCell : UITableViewCell
@property (retain, nonatomic) IBOutlet UILabel *cellName;
@property (retain, nonatomic) IBOutlet UILabel *cellAddress;

@property (retain, nonatomic) IBOutlet UILabel *cellPhone;
@property (nonatomic, retain) Business *business;
@end

BusinessCell.m

#import "BusinessCell.h"
#import "Business.h"
@implementation BusinessCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
//重写Model -- Business 类的属性setter方法为自身控件进行赋值
- (void)setBusiness:(Business *)business{
    if (_business != business) {
        [_business release];
       _business = [business retain];

    }
    //为Cell自身的控件进行赋值
    self.cellName.text = business.name;
    self.cellAddress.text = business.address;
    self.cellPhone.text = business.telephone;
}

- (void)dealloc {
    self.business = nil;
    [_cellName release];
    [_cellAddress release];
    [_cellPhone release];
    [super dealloc];
}
@end
ImageViewController.m

#import "ImageViewController.h"
#import "ASProgressPopUpView.h"
@interface ImageViewController ()<NSURLConnectionDataDelegate>

@property (retain, nonatomic) IBOutlet UILabel *detailLB;
@property (retain, nonatomic) IBOutlet UIImageView *imageShow;
@property (retain, nonatomic) NSMutableData *data;
@property (nonatomic, assign) NSUInteger totalLength; // 存储数据的总长度
@property (nonatomic, retain) ASProgressPopUpView *progressView; // 进度条
@end

@implementation ImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //进度条创建以及配置
    self.progressView = [[ASProgressPopUpView alloc] initWithFrame:CGRectMake(20, 100, 280, 0)];
    self.progressView.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:16]; // 字体

    self.progressView.popUpViewAnimatedColors = @[[UIColor redColor], [UIColor orangeColor], [UIColor greenColor]];
    self.progressView.popUpViewCornerRadius = 4.0;

    [self.progressView showPopUpViewAnimated:YES]; //显示动态框

    //添加父视图
    [self.view addSubview:self.progressView];
    //释放
    [self.progressView release];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//请求图片
- (IBAction)handleRequest:(id)sender {
    //GET请求,同步连接
    //1.创建网址字符串对象
    NSString *urlsStr = [NSString stringWithFormat:@"http://image.zcool.com.cn/56/13/1308200901454.jpg"];
    //2.如果字符串中出现中文需要URLEncode
    NSString *urlEncode = [urlsStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //3.创建NSURL对象
    NSURL *urlNS = [NSURL URLWithString:urlEncode];
    //4.创建请求对象(NSURLRequest)
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlNS];
     //5.建立连接
    /*
   NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
    //解析
   self.imageShow.image = [UIImage imageWithData:data];
     */
    //异步连接
    //1.Bloc方式
//    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        self.imageShow.image = [UIImage imageWithData:data];
//    }];
    //2.协议代理
    [NSURLConnection connectionWithRequest:urlRequest delegate:self];

}

#pragma mark - NSURLConnectionDataDelegate
//接受服务区响应触发
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //开辟空间
    self.data = [NSMutableData data];
    //获取数据的总长度
    self.totalLength = (NSUInteger)response.expectedContentLength;
}
//接受数据拼接数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [self.data appendData:data];

    CGFloat rate = self.data.length * 1.0 / self.totalLength;

    self.detailLB.text = [NSString stringWithFormat:@"进度:%.2f%%",rate * 100];
    self.progressView.progress = rate;
    //self.imageShow.image = [UIImage imageWithData:self.data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    self.imageShow.image = [UIImage imageWithData:self.data];
}

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

}

- (void)parsingJSON:(NSData *)data{

    //NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

}
- (void)dealloc {
    self.progressView = nil;
    [_imageShow release];
    [_detailLB release];
    self.data = nil;
    [super dealloc];
}
@end
时间: 2024-10-26 22:32:43

iOS中的请求(GET请求,POST请求,同步请求,异步请求)的相关文章

【Java&amp;Android开源库代码剖析】のandroid-async-http(如何设计一个优雅的Android网络请求框架,同时支持同步和异步请求)开篇

在<[Java&Android开源库代码剖析]のandroid-smart-image-view>一文中我们提到了android-async-http这个开源库,本文正式开篇来详细介绍这个库的实现,同时结合源码探讨如何设计一个优雅的Android网络请求框架.做过一段时间Android开发的同学应该对这个库不陌生,因为它对Apache的HttpClient API的封装使得开发者可以简洁优雅的实现网络请求和响应,并且同时支持同步和异步请求. 网络请求框架一般至少需要具备如下几个组件:1

[IOS_HTTP]NSURLConnection同步与异步请求

今天看到<WIN32多线程程序设计>的同步控制时,才发现原来自己对同步和异步的概念很模糊,甚至混淆.于是GOOGLE了一下.下面都是高人们的见解,简单明了. 同步是指:发送方发出数据后,等接收方发回响应以后才发下一个数据包的通讯方式.  异步是指:发送方发出数据后,不等接收方发回响应,接着发送下个数据包的通讯方式. 举个不太恰当的例子,就像:  SendMessage(...)  TRACE0("just  like  send");   PostMessage(...) 

ASIHTTP 框架,同步、 异步请求、 上传 、 下载

ASIHTTPRequest详解 ASIHTTPRequest 是一款极其强劲的 HTTP 访问开源项目.让简单的 API 完成复杂的功能,如:异步请求,队列请求,GZIP 压缩,缓存,断点续传,进度跟踪,上传文件,HTTP 认证.在新的版本中,还加入了 Objective-C 闭包 Block 的支持,让我们的代码加轻简灵活. 下面就举例说明它的 API 用法. 发起一个同步请求 同步意为着线程阻塞,在主线程中使用此方法会使应用Hang住而不响应任何用户事件.所以,在应用程序设计时,大多被用在

关于jquery同步和异步请求问题总结

关于jquery同步和异步请求问题总结 问题 这几天做项目的时候,写脚本遇到一个问题,就是jquery异步请求和同步请求执行顺序不按代码顺序执行而是最后执行导致添加数据报错,添加到空值,这怎么忍,于是我去查找jquery api,终于知道了原来jquery默认异步请求,防止数据卡死,终于让我找到了这货 async,当async: true 时,ajax请求是异步的.当async : true 时,就是同步的,但是我又有个问题,怎么设置,这个在哪设置,用$.ajax去写这个操作,不,不太麻烦了,到

jquery 同步和异步请求

1. $.ajax 同步和异步请求 1 $.ajax({ 2 type: "POST", 3 url: "some.php", 4 async : true, // true 异步,false 同步 5 // or data:{name:"John",locationi:"Boston"} 6 data: "name=John&location=Boston", 7 success: functio

C# ASP.NET Core使用HttpClient的同步和异步请求

引用 Newtonsoft.Json // Post请求 public string PostResponse(string url,string postData,out string statusCode) { string result = string.Empty; //设置Http的正文 HttpContent httpContent = new StringContent(postData); //设置Http的内容标头 httpContent.Headers.ContentType

JQuery中使用Ajax实现诸如登录名检测等异步请求Demo

上一篇博客介绍了注册登录时一次性图形验证码的工具类的编写,这篇随笔同样是我在写用jquery中ajax实现登录信息检测的异步请求功能的笔记,在各个网站进行信息用户注册时,需要在不刷新页面的情况下对注册信息进行检测并实时返回信息,比如这种情况: 对于不需要访问数据库的页面验证比较简单,一旦需要访问数据库,就比较麻烦一些,好在Jquery可以很方便的使用ajax,我写了一个简单到不能再简单的例子,效果是这样的:     下面介绍步骤及代码: 1:jsp页面(重点是jquery函数)如下: 1 <%@

js中同步与异步请求方式

异步请求方式: $.ajax({ url : 'your url', data:{name:value}, cache : false, async : true, type : "POST", dataType : 'json/xml/html', success : function (result){ do something.... } }); 同步请求方式: $.ajax({ url : 'your url', data:{name:value}, cache : false

同步、异步请求

IOS之同步请求.异步请求.GET请求.POST请求 1.同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作, 2.异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行 3.GET请求,将参数直接写在访问路径上.操作简单,不过容易被外界看到,安全性不高,地址最多255字节: 4.POST请求,将参数放到body里面.POST请求操作相对复杂,需要将参数和地址分开,不过安全性高

同步和异步请求

// //  ViewController.m //  UI-NO-18 // //  Created by Bruce on 15/8/13. //  Copyright (c) 2015年 Bruce. All rights reserved. // #import "ViewController.h" #import "InfoModel.h" @interface ViewController () @end @implementation ViewCont