如何在 iOS 中的 NSMutableURLRequest 中添加 HTTPBody?

How to add HTTPBody in NSMutableURLRequest in iOS?

我在请求中传递了 HTTPBody。但无法得到应有的回应。

下面是我的代码:

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);

输出如下:

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

那么如何设置 HTTPBody 呢?

请帮助我。

HTTPBody设置为NSData,即NS类型JSONSerializationclass.

所以你的解决方案是,制作一个 NSArray 并嵌入到 NSDictionary class 作为你的网络服务所需。

然后使用[NSJSONSerialization dataWithJSONObject:'Your dictionary' options:NSJSONWritingPrettyPrinted error:&error]来转换一个JSON 到 Data 并且它会 return 一个 NSData class 对象。

然后你添加到你的请求中, [请求 setHTTPBody: 数据]

希望对您有所帮助。如果我错误地回答了您的问题,请告诉我。