我想用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];
希望这可以帮助.