2021-06-20

网络请求的两种方式:GET 和 POST

1.普通封装方法:封装到一个类中

1、自定义一个block

typedefvoid (^DataBlock) (id data);

2、自定义GET 、POST方法

+ (void)getDataByURLString:(NSString *)urlString WithDataBlock:(DataBlock)dataBlock;

+ (void)getDataByURLString:(NSString *)urlString HttpMethod:(NSString *)method BodyString:(NSString *)bodyString DataBlock:(DataBlock)datablock;

3、实现GET、POST方法

+ (void)getDataByURLString:(NSString *)urlString WithDataBlock:( DataBlock)dataBlock{

NSURL *url = [NSURL URLWithString:urlString];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

dataBlock(data);

}];

}

+ (void)getDataByURLString:(NSString *)urlString HttpMethod:(NSString *)method BodyString:(NSString *)bodyString DataBlock:(DataBlock)datablock{

urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:urlString];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//默认是get方法,修改成post

if ([method isEqual:@"POST"]) {

[request setHTTPMethod:method];

NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:bodyData];

}

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

datablock(data);

}];

}

在ViewController中直接调用类(+)方法:

get请求:

[HttpMethod getDataByURLString:@"http://c.3g.163.com/nc/article/headline/T1348647853363/0-140.html" WithDataBlock:^(id data) {

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

NSLog(@"%@", dic); //此处就可以对数据进行具体解析

}];

post请求:

[HttpMethod getDataByURLString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx" HttpMethod:@"POST" BodyString:@"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213" DataBlock:^(id data) {

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error:n

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文主要记录笔者在ios7之前后所用的数据请求方式,以及现在常用到的AFN数据请求的封装(本文依然是笔者作为笔记使...
    耽于幽夜阅读 464评论 0 0
  • #AFNetworking源码阅读系列 一 前言: AFNetWorking一款轻量级网络请求开源框架,基于iOS...
    Xcode_破晓阅读 345评论 0 0
  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666阅读 1,443评论 0 6
  • 同步请求可以从因特网请求数据, 一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成, 才可以进行下一步操...
    小灬博阅读 894评论 2 4
  • #import "ViewController.h"#import "HttpResquestHelper.h"@...
    艾克12138阅读 341评论 0 0