我想用POST方法调用Web服务.我需要发布一个带有URL的字典.我的Web服务参数如下:
ConversationMessage { authorUserId (string,optional),subject (string,hasAttachment (boolean,conversationId (string,attachment (DigitalAsset,content (string,title (string,urgency (boolean,searchable (Map[String,Object],optional) } DigitalAsset { id (string,assetUrl (string,assetContent (string,thumbGenerated (boolean,fileName (string,optional) } Map[String,Object] { empty (boolean,optional) }
以下是我的要求:
NSMutableArray *arr=[[NSMutableArray alloc]init]; NSMutableDictionary *dict=[[NSMutableDictionary alloc]init]; [dict setValue:@"test title" forKey:@"title"]; [dict setValue:@"test message" forKey:@"content"]; [dict setValue:@"0" forKey:@"urgency"]; [arr addObject:[NSMutableDictionary dictionaryWithObject:dict forKey:@"ConversationMessage"]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; [request setURL:[NSURL URLWithString:strUrl]]; [request setTimeoutInterval:10.0]; [request setHTTPMethod:strMethod]; NSString *boundary = @"---------------------------14737809831466499882746641449"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *body=[[NSMutableData alloc]init]; for (NSMutableDictionary *dict in array) { NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL]; [body appendData:jsonData]; } [request setHTTPBody:body];
但是我收到以下错误:
服务器拒绝此请求,因为请求实体的格式不受所请求方法所请求资源的支持
解决方法
请找到以下代码,将数据发布到Web服务.请注意这是我在我的一个申请中使用的样本.
//json format to send the data jsondata = [NSJSONSerialization dataWithJSONObject:"NSDictionary variable name" options:NSJSONWritingPrettyPrinted error:&error]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:theUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setHTTPMethod:@"POST"]; [request setValue:[NSString stringWithFormat:@"%d",[jsondata length]] forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:jsondata];
希望这可以帮助.
从您的评论“服务器拒绝此请求”服务器是否支持JSON或XML格式.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。