• 基于AFNetWorking封装一个网络请求数据的类


    1.新建一个继承于NSObject类的类,在.h文件中

    #import "AFHTTPRequestOperationManager.h"

    //定义两个block来接收请求成功和失败

    typedef  void(^DownLoadFinishedBlock)(id responseObj);

    typedef void (^DownLoadFialedBlock)(NSError*error);

    @interface NetManager : NSObject

    //Get请求的方法封装

    +(void)doGetWithUrlStr:(NSString*)urlString contentType:(NSString*)type finished:(DownLoadFinishedBlock)finished failure:(DownLoadFialedBlock)fialed;

    //Post请求的方法封装

    +(void)doPostWithUrlStr:(NSString*)urlString parameters:(NSDictionary*)dic contentType:(NSString*)type finished:(DownLoadFinishedBlock)finished failure:(DownLoadFialedBlock)fialed;

    2.下面是封装方法的实现:

    #import "NetManager.h"

    @implementation NetManager

    //Get请求的方法

    +(void)doGetWithUrlStr:(NSString*)urlString contentType:(NSString*)type finished:(DownLoadFinishedBlock)finished failure:(DownLoadFialedBlock)fialed{

      //创建manager对象

        AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];

      //设置请求的数据类型

        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:type, nil];

        [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

      //请求成功

            finished(responseObject);

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

      //请求失败

            fialed(error);

        }];

    }

    //Post请求的方法

    //说明:parameters:参数,即使用post请求时需要传给后台服务器的参数,在这里我们应封装成一个字典类型的数据,然后把这个字典当做参数传过去。

    +(void)doPostWithUrlStr:(NSString*)urlString parameters:(NSDictionary*)dic contentType:(NSString*)type finished:(DownLoadFinishedBlock)finished failure:(DownLoadFialedBlock)fialed

    {

      //创建manager对象  

        AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];

      //设置请求的数据类型  

        manager.responseSerializer = [AFHTTPResponseSerializer serializer];

        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:type, nil];

        [manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {

             finished(responseObject);

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            fialed(error);

        }];

    }

    @end

  • 相关阅读:
    An exception was thrown while activating Castle.Proxies.PersonAppServiceProxy. ABP Netcore
    abp 深坑三 Unable to cast object of type 'System.Double' to type 'System.Single'.System.InvalidCastException: Unable to cast object of type 'System.Double' to type 'System.Single'.
    《统计学习方法》笔记--奇异值分解
    《统计学习方法》笔记--聚类方法
    《统计学习方法》笔记--条件随机场
    《统计学习方法》笔记--EM算法
    统计学习方法》笔记--提升方法(二)
    《统计学习方法》笔记--提升方法
    《统计学习方法》笔记--决策树
    《统计学习方法》笔记--逻辑回归
  • 原文地址:https://www.cnblogs.com/MasterPeng/p/5292427.html
Copyright © 2020-2023  润新知