我在请求中传递了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,这是NSJSONSerialization类的类型。

因此,您的解决方案将是,制作一个NSArray并嵌入到您的Web服务所需的NSDictionary类中。

然后使用[NSJSONSerialization dataWithJSONObject:'Your dictionary'选项:NSJSONWritingPrettyPrinted错误:&error]将JSON转换为Data,它将返回NSData类obj。

然后,您将请求添加为
[请求setHTTPBody:数据]

希望这会帮助你。如果我听错了您的问题,请告诉我。

关于ios - 如何在iOS的NSMutableURLRequest中添加HTTPBody?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40602617/

10-13 04:13