Search code examples
iosios10nsmutableurlrequest

How to add HTTPBody in NSMutableURLRequest in iOS?


I am passing HTTPBody in my request. But its unable to get proper response.

below is my code :

NSURL *url = [NSURL URLWithString:@"https://sample.ios.com/l1/voucher"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];

[request setValue:@"text/html; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

//Now pass your own parameter --------

[request setValue:@"g064a4b5aa95556a7b0b4435d94c317840e9b456" forHTTPHeaderField:@"X-Authorization"];
[request setValue:@"123651236512" forHTTPHeaderField:@"uuid"];
[request setValue:@"myIphone" forHTTPHeaderField:@"devicename"];


NSString *myRequestString =@"voucher=JHAHSDGH-80";
NSLog(@"%@",myRequestString);
NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
[ request setHTTPBody: myRequestData ];

NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(@"content : %@",content);

Output is coming like below :

content : {"voucher":["The voucher field is required."]}

So how can I set HTTPBody ?

Please help me.


Solution

  • HTTPBody is set to be as NSData, Which is the type of NSJSONSerialization class.

    So your solution would be, make an NSArray and embedded into NSDictionary class as your web services required.

    Then use [NSJSONSerialization dataWithJSONObject:'Your dictionary' options:NSJSONWritingPrettyPrinted error:&error] To convert a JSON into Data And it will return a NSData class obj.

    Then you add to your request as, [request setHTTPBody: Data]

    Hope this will help you. Let me know if I got your question wrongly.