【问题标题】:objective c ios http request sent not encoded string目标c ios http请求发送未编码字符串
【发布时间】:2012-08-10 13:20:57
【问题描述】:

是否可以设置为http body不编码字符串?

  NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

  NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

  [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  [request setHTTPBody:postData];

是否可以这样做:

  NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
  [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  [request setHTTPBody:postString];

我试过这个并得到一个错误: 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[__NSCFString bytes]:无法识别的选择器发送到实例

【问题讨论】:

  • 你试过了吗?我的猜测是它会起作用。
  • 你要发布数据,没有理由设置Content-Length,因为它会根据body来设置。
  • 来自 NSURLRequest - (NSData *)HTTPBody

标签: objective-c ios request


【解决方案1】:
[request setHTTPBody:postString];

应该是

[request setHTTPBody:postData];

【讨论】:

  • 其实这个答案有点对。至少对我帮助很大! setHTTPBody 方法接受一个 NSData 对象而不是一个 NSString 对象。因此,您必须使用 [postString dataUsingEncoding:NSUTF8StringEncoding] 或 NSASCIIStringEncoding 将 HTTPBody 字符串对象编码为 NSData 对象。
猜你喜欢
  • 1970-01-01
  • 2013-05-13
  • 2022-11-30
  • 2012-12-29
  • 2014-04-12
  • 1970-01-01
  • 2012-12-11
  • 2016-04-26
  • 2012-08-30
相关资源
最近更新 更多