使用 NSURLSession 发布带有原始正文的请求 [英] Post request with raw body using NSURLSession

查看:59
本文介绍了使用 NSURLSession 发布带有原始正文的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直卡在这里.下面是我使用 NSURLSession 使用原始正文发布请求的代码.我得到 response = NULL 并且没有错误.

I have stuck here. Below is my code for Post request with raw body using NSURLSession. I got response = NULL and no error.

NSString* stringRequest = @"https://chocudan.com/api/shops/by_ids";
NSURL* urlRequest = [NSURL URLWithString:stringRequest];

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:urlRequest];
request.HTTPMethod = @"POST";

NSString* bodyRequest = @"563c268b84ba489c4729f149";

//I have to tried a base64 convert here but still not work.
//request.HTTPBody = [NSData base64DataFromString:bodyRequest];

request.HTTPBody = [bodyRequest dataUsingEncoding:NSUTF8StringEncoding];


NSURLSessionConfiguration* configureSession = [NSURLSessionConfiguration defaultSessionConfiguration];

configureSession.HTTPAdditionalHeaders = @{@"Content-Type" : @"application/json charset=utf-8",
                                           @"Content-Lenght" : @"180"};

NSURLSession* session = [NSURLSession sessionWithConfiguration:configureSession];

NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;

    if (!error && respHttp.statusCode == 200) {

        NSDictionary* respondData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

        NSLog(@"%@", respondData);
    }else{

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

}];

[dataTask resume];

我必须与邮递员一起尝试,一切正常.这是图片.

I have to try with postman and everything work fine. This is pictures.

提前致谢.

推荐答案

也试试改一下

    NSArray* bodyArray = @[@"563c268b84ba489c4729f149"]
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bodyArray 
          options:NSJSONWritingPrettyPrinted error:&error];
   request.HTTPBody = jsonData;

这篇关于使用 NSURLSession 发布带有原始正文的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆