post请求传递JSON数据类型
报错:JSON text did not start with array or object and option to allow fragments not set
问题一:如何上传JSON类型的数据
解答:
NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init];
[jsonDic setObject:self.model.treeid forKey:@"treeId"];
[jsonDic setObject:self.caseId forKey:@"caseId"];
[jsonDic setObject:self.imageArray forKey:@"pictureMD5s"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:0 error:&error];
NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *urlStr = [NSString stringWithFormat:@"%s/case/pat/picture/create",APPURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlStr]];
request.HTTPMethod = @"POST";
request.HTTPBody = [json dataUsingEncoding:NSUTF8StringEncoding];
以上是上传部分
问题二:=Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
Error 415 Unsupported Media Type
HTTP ERROR 415
解答:
需要设置Content-Type这个字段@"application/json;charset=utf-8"(必须加utf-8)
将请求头的Content-Type 设置为@"application/json;charset=utf-8"类型,满足该接口的请求头规范
[request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
就是因为没加;charset=utf-8,卡住死活解决不了,难受。。。。。。。。。
不过终于解决了。
😁 有帮助到你就点个赞呗!😁