我想用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格式.