• 基于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

  • 相关阅读:
    java 集合排序
    java传值和传址
    Dom4j操作xml
    JAXP操作xml
    乐观锁和悲观锁【转】
    java IO【转】
    java 可变参数
    Eclipse调试Java的10个技巧【转】
    编译JDK源代码【转】
    Access restriction: The method typeNameToClass(String) from the type ObjectHandler is not accessible due to restriction on required library
  • 原文地址:https://www.cnblogs.com/MasterPeng/p/5292427.html
Copyright © 2020-2023  润新知