Sun*_*hah 6 json objective-c nsmutableurlrequest ios
我想用这个POST方法调用一个Web服务.我需要发布一个带有URL的字典.我的Web服务参数如下:
ConversationMessage {
authorUserId (string, optional),
subject (string, optional),
hasAttachment (boolean, optional),
conversationId (string, optional),
attachment (DigitalAsset, optional),
content (string, optional),
title (string, optional),
urgency (boolean, optional),
searchable (Map[String,Object], optional)
}
DigitalAsset {
id (string, optional),
assetUrl (string, optional),
assetContent (string, optional),
thumbGenerated (boolean, optional),
fileName (string, optional)
}
Map[String,Object] {
empty (boolean, optional)
}
Run Code Online (Sandbox Code Playgroud)
以下是我的要求:
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];
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
服务器拒绝此请求,因为请求实体的格式不受所请求方法所请求资源的支持
请找到以下代码,将数据发布到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];
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
从您的评论"服务器拒绝此请求"服务器是否支持JSON或XML格式.
NSMutableURLRequest有一个方法setHTTPBody:将您NSData* jsonData作为参数。从表面上看,这似乎是你的问题。你永远不会在上面的代码中调用它。