zoukankan      html  css  js  c++  java
  • AFNetworking使用

    • 简介

    AFNetworking,是对NSURLConnection、NSURLSession的一层封装

    • 常用类

    AFHTTPRequestOperationManager

    是AFN中最重要的对象之一

    封装了HTTP请求的常见处理

    GETPOST请求

    解析服务器的响应数据

    • GETPOST请求

    GET请求

    - (AFHTTPRequestOperation *)GET:(NSString *)URLString

                         parameters:(id)parameters

                            success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

                            failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

    POST请求

    - (AFHTTPRequestOperation *)POST:(NSString *)URLString

                          parameters:(id)parameters

                             success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

                             failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

    • 具体使用步骤

    1.创建管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

    2.封装请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"username"] = @"Test";
    params[@"pwd"] = @"123";

    3.发送请求

    NSString *url = @"http://localhost:8080/Server/login";
    [mgr POST:url parameters:params
    success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // 请求成功的时候调用这个block
    NSLog(@"请求成功---%@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // 请求失败的时候调用调用这个block
    NSLog(@"请求失败");
    }];
    // GET请求
    [mgr GET:url parameters:params
    success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // 请求成功的时候调用这个block
    NSLog(@"请求成功---%@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // 请求失败的时候调用调用这个block
    NSLog(@"请求失败");
    }];

    4.对服务器返回数据的解析
    1.AFN可以自动对服务器返回的数据进行解析
    * 默认将服务器返回的数据当做JSON来解析

    2.设置对服务器返回数据的解析方式
    1> 当做是JSON来解析(默认做法)
    * mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    * responseObject的类型是NSDictionary或者NSArray

    2> 当做是XML来解析
    * mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
    * responseObject的类型是NSXMLParser

    3> 直接返回data
    * 意思是:告诉AFN不要去解析服务器返回的数据,保持原来的data即可
    * mgr.responseSerializer = [AFHTTPResponseSerializer serializer];

  • 相关阅读:
    在图像中随机更改像素值程序——matlab
    图像频谱图画图——matlab
    图像三维灰度分布图——matlab
    JVM安全退出(如何优雅的关闭java服务)
    annotation(@Retention@Target)详解
    synchronized与static synchronized 的区别
    ExecutorService对象的shutdown()和shutdownNow()的区别
    execute和submit的区别
    Java线程之FutureTask与Future浅析
    Runnable与Callable
  • 原文地址:https://www.cnblogs.com/H7N9/p/4928826.html
Copyright © 2011-2022 走看看