1

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.

sunsunai
  • 161
  • 4
  • 11

5 Answers5

3

Try changing it too

    NSArray* bodyArray = @[@"563c268b84ba489c4729f149"]
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bodyArray 
          options:NSJSONWritingPrettyPrinted error:&error];
   request.HTTPBody = jsonData;
Mihir Mehta
  • 13,743
  • 3
  • 64
  • 88
  • then its become an NSArray and when I going to change everything it's still the same – sunsunai Dec 17 '15 at 07:06
  • that's correct... you need to pass nsarray and convert that in nsdata using NSJSONSerialization.dataWithJSONObject – Mihir Mehta Dec 17 '15 at 07:08
  • sorry, I can't understand what do you mean. Why we use NSJSONSerialization.dataWithJSONObject when I want get Json from response ? – sunsunai Dec 17 '15 at 07:18
  • beacuse you want to pass data as body ... and body's format is in array structure ... so you need to create array ... but httpbody expects NSData so to convert your array into NSData you'll use dataWithJSONObject method – Mihir Mehta Dec 17 '15 at 07:28
  • i have updated my answer ... see if you can understand what i am trying tell – Mihir Mehta Dec 17 '15 at 07:31
  • thank you very much. with you solusion and i need to set some value and key for request and all working fine. – sunsunai Dec 17 '15 at 08:58
1

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;
rayryeng
  • 102,964
  • 22
  • 184
  • 193
0

This fixed it for me:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = ["Content-Type" : "text/plain"]
primulaveris
  • 966
  • 14
  • 20
  • I have to fixed my problems but I will try your solution later. Thank you. – sunsunai Dec 18 '15 at 01:24
  • See his postman example. The content is of type json, not text. However, the content-type must be something the server deals with. Do not expect that APIs do everything right automatically. :-) – Hermann Klecker Feb 08 '17 at 19:15
0

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.

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71
0

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.

Thomas Wang
  • 2,233
  • 2
  • 14
  • 24
marvin
  • 211
  • 1
  • 3