我在请求中传递了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?
请帮帮我。
答案 0 :(得分:2)
HTTPBody设置为NSData,这是NSJSONSerialization类的类型。
所以你的解决方案是,制作一个NSArray并嵌入到NSDictionary类中作为你需要的Web服务。
然后使用 [NSJSONSerialization dataWithJSONObject:'您的词典' options:NSJSONWritingPrettyPrinted error:& error] 将JSON转换为数据并返回NSData类obj。
然后您添加到您的请求中, [请求setHTTPBody:数据]
希望这会对你有所帮助。如果我错误地提出你的问题,请告诉我。