Post request with raw body using NSURLSession

2019-06-08 14:51发布

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. test with postman

Thank in advance.

5条回答
Explosion°爆炸
2楼-- · 2019-06-08 14:56

My raw data was like :

{
"email":"test@gmail.com",
"password":"12345678"
}

and what I did is :

NSMutableDictionary *dict  = [[NSMutableDictionary alloc] init];
[dict setValue:@"test@gmail.com" forKey:@"email"];
[dict setValue:@"12345678" forKey:@"password"];

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                  options:NSJSONWritingPrettyPrinted error:&error];
                  request.HTTPBody = jsonData;
查看更多
孤傲高冷的网名
3楼-- · 2019-06-08 15:08

This fixed it for me:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = ["Content-Type" : "text/plain"]
查看更多
太酷不给撩
4楼-- · 2019-06-08 15:14

Try changing it too

    NSArray* bodyArray = @[@"563c268b84ba489c4729f149"]
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bodyArray 
          options:NSJSONWritingPrettyPrinted error:&error];
   request.HTTPBody = jsonData;
查看更多
小情绪 Triste *
5楼-- · 2019-06-08 15:15

I guess that it was not data that was null but respondData was null?

That is because your service sends an Array with exactly one Object. JSONSerialisation creates an NSArray from that with one NSDictionary in it. The dictionary has the keys _id, contact and so on.

So it is

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

BTW

 NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;

does not make much of a sense but does not harm either.

With respect to the body of your request, see mihir's answer. He is just right. It may help you understanding mihir's point when you do this:

NSString* bodyRequest = @"[563c268b84ba489c4729f149]";

However, this is rather quick & dirty but may help you understanding the principles. Once understood you will certainly follow mihir's suggestion.

查看更多
在下西门庆
6楼-- · 2019-06-08 15:17

If you want to post raw, and param is a format of NSString, you only need to do this:

NSData *param_data = [encry_str dataUsingEncoding:NSUTF8StringEncoding];
murequest.HTTPBody = param_data;

If we can’t get anything from that response, notice that the response serializer is correct. Any additional settings, please deal it with server.

查看更多
登录 后发表回答