iOS 之get和post请求

//建立一个类,在.h文件里写属性

#import <Foundation/Foundation.h>

@interface MyModel : NSObject

@property (nonatomic, copy)NSString *name;

@property (nonatomic, copy)NSString *street_id;

@property (nonatomic, copy)NSString *telephone;

@property (nonatomic, copy)NSString *uid;

@property (nonatomic, copy)NSString *adress;

@property (nonatomic, copy)NSString *location;

@property (nonatomic, copy)NSString *lat;

@property (nonatomic, copy)NSString *lng;

@end


//在请求数据的.h文件里签订协议,自定义属性

#import <UIKit/UIKit.h>

#import "MyModel.h"

@interface RootViewController : UIViewController  <UITableViewDataSource, UITableViewDelegate, NSURLConnectionDataDelegate>

@property (nonatomic, retain)NSMutableArray *allArray;

@property (nonatomic, retain)UITableView *tableView;

@property (nonatomic, retain)NSMutableData *data;

@end


//在请求数据的.m文件里

#import "RootViewController.h"

#import "MyTableViewCell.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)dealloc

{

    [_allArray release];

    [_tableView release];

    [_data release];

    [super dealloc];

}

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor redColor];

   /*

    [self buttonAction];

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 375, 500) style:UITableViewStylePlain];

    self.tableView.backgroundColor = [UIColor greenColor];

    [self.view addSubview:self.tableView];

    [_tableView release];

    self.tableView.delegate = self;

    self.tableView.dataSource = self;

    

//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

//    button.frame = CGRectMake(100, 550, 100, 100);

//    button.backgroundColor = [UIColor grayColor];

//    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

//    [self.view addSubview:button];*/

 

    /*

        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];

        button1.frame = CGRectMake(100, 550, 100, 100);

        button1.backgroundColor = [UIColor grayColor];

        [button1 addTarget:self action:@selector(button1Action:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:button1];

    */

    /*

    

    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];

    button2.frame = CGRectMake(100, 550, 100, 100);

    button2.backgroundColor = [UIColor grayColor];

    [button2 addTarget:self action:@selector(button2Action:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button2];

*/

    

    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];

    button3.frame = CGRectMake(100, 550, 100, 100);

    button3.backgroundColor = [UIColor grayColor];

    [button3 addTarget:self action:@selector(button3Action:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button3];

}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

- (void)button3Action:(UIButton *)button

{

    NSLog(@"post 异步");

    NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];             [request setHTTPMethod:@"POST"];

    NSString *bodyStr = @"date=20131129&startRecord=5&len=5&udid=1234567890&terminalType=Iphone&cid=215";

    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:bodyData];

    //post 异步请求  block

    //参数1. request对象

    //参数2. 多线程队列NSOperationQueue对象

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

#pragma mark --- 遇到block 一定是回调回来的参数就是你需要的数据

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

       NSLog(@"dic ====== %@", dic);

       

   }];

}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

//***********************************************************************************

- (void)button2Action:(UIButton *)button

{

    NSLog(@"get异步");

    

    NSString *str = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";

    

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

#pragma mark ---- 设置异步请求代理

    [NSURLConnection connectionWithRequest:request delegate:self];

    

}

#pragma mark --- 收到服务器响应

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"response = %@", response);

    self.data = [NSMutableData data];

}

#pragma mark --- 接收数据

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

{

    //接收data对象

    [self.data appendData:data];

}

#pragma mark -- 数据请求完成

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

//    NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:self.data options:0 error:nil];

//    NSLog(@"%@", array);

    

    //显示图片

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 100, 275, 400)];

    imageView.backgroundColor = [UIColor yellowColor];

    imageView.image = [UIImage imageWithData:self.data];

    [self.view addSubview:imageView];

    [imageView release];

}

#pragma mark --- 数据请求失败

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

{

    NSLog(@"数据请求失败");

}

//***********************************************************************************

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

- (void)button1Action:(UIButton *)button

{

    NSLog(@"post异步");

    NSString *str =  @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //设置请求方式为post

    [request setHTTPMethod:@"POST"];

    //设置body

    //设置参数

    NSString *bodyStr = @"date=20131129&startRecord=5&len=5&udid=1234567890&terminalType=Iphone&cid=215";

    //将参数转换为data类型

    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

    //设置请求对象的body

    [request setHTTPBody:bodyData];

    NSURLResponse *response = nil;

    //创建错误信息对象

    NSError *error = nil;

    //3.像服务器发送请求

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

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

    NSLog(@"dic ==== %@", dic);

    NSLog(@"respose === %@", response);

}

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *cellIndefi = @"reuse";

    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndefi];

    if (cell == nil) {

        cell = [[MyTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIndefi];

    }

    MyModel *model = [self.allArray objectAtIndex:indexPath.row];

    NSLog(@"model ===== %@", model);

    cell.model = model;

    return cell;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    NSLog(@"allArray ====== %@", self.allArray);

    return self.allArray.count;

}

//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

- (void)buttonAction

{

    NSLog(@"get同步");

    NSString *URLStr = @"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";

    //对文本进行编码

    NSString *URLStrEcode = [URLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    //1.创建URL地址

    NSURL *URL = [NSURL URLWithString:URLStrEcode];

    //2.创建请求对象

    NSMutableURLRequest *URLRequest = [NSMutableURLRequest requestWithURL:URL];

    //创建服务器响应信息对象

    NSURLResponse *response = nil;

    //创建错误信息对象

    NSError *error = nil;

    //3.像服务器发送请求

    NSData *data = [NSURLConnection sendSynchronousRequest:URLRequest returningResponse:&response error:&error];

    NSLog(@"\nresponse = %@", response);

    NSLog(@"\nerror = %@", error);

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

    

    NSMutableArray *resultArray = [dic objectForKey:@"results"];

    self.allArray = [NSMutableArray array];

    NSLog(@"self.allArray ===== %@", self.allArray);

    for (NSMutableDictionary *dicctionary in resultArray) {

        MyModel *model = [[MyModel alloc]init];

        model.name = [dicctionary objectForKey:@"name"];

        model.street_id = [dicctionary objectForKey:@"street_id"];

        model.telephone = [dicctionary objectForKey:@"telephone"];

        model.uid = [dicctionary objectForKey:@"uid"];

        model.adress = [dicctionary objectForKey:@"address"];

        NSMutableDictionary *dicLoction = [dicctionary objectForKey:@"location"];

        model.lat = [dicLoction objectForKey:@"lat"];

        model.lng = [dicLoction objectForKey:@"lng"];

//        NSLog(@"-----lat = %@", model.lat);

//        NSLog(@"-----lng = %@", model.lng);

        [self.allArray addObject:model];

}

     NSLog(@"dic = %@", dic);

//    [self.tableView reloadData];

}

//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    MyModel *model = [self.allArray objectAtIndex:indexPath.row];

    CGFloat height = [MyTableViewCell heightForContent:model.adress];

    return height + 80;

}

- (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.

}

*/

@end


//在自定义cell的.h文件里,自定义属性

#import <UIKit/UIKit.h>

#import "MyModel.h"

@interface MyTableViewCell : UITableViewCell

@property (nonatomic, retain)MyModel *model;

@property (nonatomic, retain)UILabel *lable;

@property (nonatomic, retain)UILabel *lable1;

+ (CGFloat)heightForContent:(NSString *)text;

@end


////在自定义cell的.h文件里,自适应高度

#import "MyTableViewCell.h"

@implementation MyTableViewCell

- (void)awakeFromNib {

    // Initialization code

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];


    // Configure the view for the selected state

}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

        [self creatSubView];

    }

    return self;

}

- (void)creatSubView

{

    self.lable = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, 300, 30)];

    self.lable.backgroundColor = [UIColor whiteColor];

    self.lable.numberOfLines = 0;

    [self.contentView addSubview:self.lable];

    [_lable release];

    

    

    self.lable1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 60, 300, 30)];

    self.lable1.backgroundColor = [UIColor whiteColor];

    self.lable1.numberOfLines = 0;

    [self.contentView addSubview:self.lable1];

    [_lable1 release];

}

- (void)setModel:(MyModel *)model

{

    if (_model != model) {

        [_model release];

        _model = [model retain];

        

    }

    self.lable.text = _model.name;

    self.lable1.text = _model.adress;

    //计算内容高度

    CGFloat lable1Heighth = [[self class]heightForContent: _model.adress];

    //改变lable1的高度

    CGRect frame = self.lable.frame;

    frame.size.height = lable1Heighth;

    self.lable.frame = frame;

}

+ (CGFloat)heightForContent:(NSString *)text

{

    CGSize size = CGSizeMake(300, 2000);

    //NSStringDrawingUsesLineFragmentOrigin 字体与显示字体大小一致

    //按行计算内容高度

    //创建存放字体的字典, 字体大小要与lable1字体大小一致,即与显示他的lable的字体大小一致

    //代码固定

    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName];

    CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];

    

    return frame.size.height;

}


@end





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值