zoukankan      html  css  js  c++  java
  • 基于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

  • 相关阅读:
    经过我修改的一个记录集分页插件(C#)[原创]
    基于javascript的asp数据库操作类,含分页、字符串截取、用户登陆验证[原创]
    .net中关于windows身份验证的一个教训[原创]
    IE功能汇总[网上收集]
    一些珍藏代码[网上收集]
    对以前改的c#分页插件的补充[原创]
    ASP验证码图形生成[网上收集]
    关于嵌套使用DataList的心得[原创]
    浏览器标签显式网页logo
    金日开博
  • 原文地址:https://www.cnblogs.com/MasterPeng/p/5292427.html
Copyright © 2011-2022 走看看