Post request with raw body using NSURLSession

我怕爱的太早我们不能终老 提交于 2019-12-06 21:36:45

Try changing it too

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

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;

This fixed it for me:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = ["Content-Type" : "text/plain"]

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.

mac

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!