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

  • 相关阅读:
    PAT 甲级 1040 Longest Symmetric String
    POJ 1276 Cash Machine
    #Leetcode# 349. Intersection of Two Arrays
    #Leetcode# 922. Sort Array By Parity II
    【USACO题库】3.1.2 Score Inflation总分
    【USACO题库】3.4.4 Raucous Rockers“破锣摇滚”乐队
    【USACO题库】3.4.2 American Heritage美国血统
    【USACO题库】3.3.5 A Game游戏
    【USACO题库】3.3.4 Home on the Range家的范围
    【USACO题库】3.3.1 Riding the Fences骑马修栅栏
  • 原文地址:https://www.cnblogs.com/MasterPeng/p/5292427.html
Copyright © 2011-2022 走看看