接口调通

三种联调接口的方式:

1.苹果原生
2.AFN请求
3.YTK猿题库对AFN的再封装

1.苹果原生 —- 用于排除其他不良因素,保证最基本需求

- (void)startAppleWay {
    // 1.创建一个网络路径
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.16.38.81:8080/moto/app/login.do"]];

    // 2.创建一个网络请求,分别设置请求方法、请求参数
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/mjson;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];


    NSDictionary *header = @{
                            @"cmd":@"login",
                            @"msgId":@"123456789",
                            };
    NSDictionary *body = @{
                           @"phone":@"123456",
                           @"password":@"123456",
                           };
    //请求体
    NSDictionary *args = @{
                           @"header":header,
                           @"body":body,
                           };

    //Json请求体
    request.HTTPBody =  [NSJSONSerialization dataWithJSONObject:args options:NSJSONWritingPrettyPrinted error:nil];;


    // 3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];

    // 4.根据会话对象,创建一个Task任务
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"从服务器获取到数据");
        /*
         对从服务器获取到的数据data进行相应的处理.
         */
        if (error) {
            NSLog(@"%@",error);

        }else{
            if (data) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];

                NSLog(@"%@",dict);
            }

        }

    }];

    //5.最后一步,执行任务,(resume也是继续执行)。
    [sessionDataTask resume];
}

1.AFN请求 —- 基本方法,设置了请求头,并自定返回格式

- (void)AFNLogin {

    //请求体
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSDictionary *header = @{
                             @"cmd":@"login",
                             @"msgId":@"123456789",
                             };
    NSDictionary *body = @{
                           @"phone":@"123456",
                           @"password":@"123456",
                           };
    params[@"header"] = header;
    params[@"body"] = body;


    //manager管理类
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    //请求方式和服务器地址
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"http://172.16.38.81:8080/moto/app/login.do" parameters:nil error:nil];

//    manager.securityPolicy = [self customSecurityPolicy];

    //请求头
    [req setValue:@"application/mjson;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

    //请求体
    [req setHTTPBody:[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil]];


    //添加返回解析格式  application/mjson
    AFHTTPResponseSerializer *serializer =manager.responseSerializer ;

    NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:serializer.acceptableContentTypes];

    [contentTypes addObject:@"application/mjson"];


    serializer.acceptableContentTypes = contentTypes;

    //开始请求
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        if (!error) {
            NSLog(@"Reply JSON: %@", responseObject);
        } else {

            NSLog(@"Error: %@, %@, %@", error, response, responseObject);


        }
    }] resume];

}

3– YTK方式—

猿题库的代码没有跑通,开始排查错误:

1.其他网站能否跑通

测试了豆瓣api的快速入门 get图书信息,可以获取到数据,说明本身库没问题

2016-10-08 10:38:55.085 TestYTKNetwork[1830:577216] Add request: BookInfoApi
2016-10-08 10:38:55.300 TestYTKNetwork[1830:577311] Finished Request: BookInfoApi
2016-10-08 10:38:56.966 TestYTKNetwork[1830:577216] success
2016-10-08 10:38:56.966 TestYTKNetwork[1830:577216] {"rating":{"max":10,"numRaters":354,"average":"7.0","min":0},"subtitle":"","author":["[日] 片山恭一"],"pubdate":"2005-1","tags":[{"count":141,"name":"片山恭一","title":"片山恭一"},{"count":67,"name":"日本","title":"日本"},{"count":64,"name":"日本文学","title":"日本文学"},{"count":39,"name":"小说","title":"小说"},{"count":33,"name":"满月之夜白鲸现","title":"满月之夜白鲸现"},{"count":15,"name":"爱情","title":"爱情"},{"count":9,"name":"純愛","title":"純愛"},{"count":7,"name":"外国文学","title":"外国文学"}],"origin_title":"","image":"https://img3.doubanio.com\/mpic\/s1747553.jpg","binding":"平装","translator":["豫人"],"catalog":"\n      ","pages":"180","images":{"small":"https://img3.doubanio.com\/spic\/s1747553.jpg","large":"https://img3.doubanio.com\/lpic\/s1747553.jpg","medium":"https://img3.doubanio.com\/mpic\/s1747553.jpg"},"alt":"https:\/\/book.douban.com\/subject\/1220562\/","id":"1220562","publisher":"青岛出版社","isbn10":"7543632608","isbn13":"9787543632608","title":"满月之夜白鲸现","url":"https:\/\/api.douban.com\/v2\/book\/1220562","alt_title":"","author_intro":"","summary":"那一年,是听莫扎特、钓鲈鱼和家庭破裂的一年。说到家庭破裂,母亲怪自己当初没有找到好男人,父亲则认为当时是被狐狸精迷住了眼,失常的是母亲,但出问题的是父亲……。","price":"15.00元"}
2016-10-08 10:38:56.970 TestYTKNetwork[1830:577216] Request queue size = 0

2.排除一下可能出错原因

404 – 请求的网页不存在-原来写成豆瓣的了,将豆瓣的改掉

再次确认一下网址能不能通,结果显示超时

进入YTK源码,看下请求的URL 参数是否正确,断点打印,基本正确

Printing description of param:
{
    body =     {
        password = 123456;
        phone = 6;
    };
    header =     {
        cmd = login;
        msgId = 123456789;
    };
}
Printing description of requestSerializer:
<AFHTTPRequestSerializer: 0x7f83b3c026a0>

Printing description of headerFieldValueDictionary:
{
    "Content-Type" = "application/mjson;charset=UTF-8";
}

Printing description of request:
<NSMutableURLRequest: 0x7f83b3dd8880> { URL: http://172.16.38.81:8080/moto/app/login.do }

请求参数都是正确的,那只能对AFN返回的Response进行截获看看

AFN也显示超时——-好奇怪,还是参数或者域名的问题

用AFN原生也超时——服务器挂了 —- 需要服务器做支持

Printing description of error:
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7fcaa96c3260 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://172.16.38.81:8080/moto/app/login.do, NSErrorFailingURLKey=http://172.16.38.81:8080/moto/app/login.do, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}

AFN可以返回结果了, 查看AFN返回的Response

截获到YTK调用的AFN返回数据的源码部分,发现数据不能够解析,是乱码,

有可能是body发送的时候需要JSON序列化,需要服务器联调一下

— 服务器告知,发送的都是 a=111&b=888&c=2222这样的数据,不是服务器需要的数据格式,因此就返回了 错误信息

之前做AFN操作的时候,做了相关处理,具体处理是 将请求体JSON化后上传

 //请求体
    [req setHTTPBody:[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil]];

对应到YTK的代码里面,需要修改的地方是把这个HTTP的序列化改成JSON就好

- (YTKRequestSerializerType)requestSerializerType {
    return YTKRequestSerializerTypeJSON;
}

再跑一次- 成功了

打印结果:

2016-10-08 14:34:11.079 TestYTKNetwork[2601:1378204] Add request: LoginApi
2016-10-08 14:34:11.179 TestYTKNetwork[2601:1378620] Finished Request: LoginApi
2016-10-08 14:34:11.180 TestYTKNetwork[2601:1378204] success
2016-10-08 14:34:11.180 TestYTKNetwork[2601:1378204] Request queue size = 0
2016-10-08 14:37:31.853 TestYTKNetwork[2601:1378204] Add request: LoginApi
2016-10-08 14:37:35.116 TestYTKNetwork[2601:1391017] Finished Request: LoginApi
Printing description of request->_responseString:
{"header":{"code":0,"cmd":"login","msgId":"123456789"},"body":{"userInfo":{"header":null,"nickName":null,"gender":null,"phone":"6","userId":20,"openId":null,"regisFrom":0},"token":"14|TFkqsObeOvNUT"}}
Printing description of request->_responseObject:
{
    body =     {
        token = "14|TFkqsObeOvNUT";
        userInfo =         {
            gender = "<null>";
            header = "<null>";
            nickName = "<null>";
            openId = "<null>";
            phone = 6;
            regisFrom = 0;
            userId = 20;
        };
    };
    header =     {
        cmd = login;
        code = 0;
        msgId = 123456789;
    };
}}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值