ios – 在HTTPBody中设置NSDictionary并使用POST方法发送

前端之家收集整理的这篇文章主要介绍了ios – 在HTTPBody中设置NSDictionary并使用POST方法发送前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想用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格式.

猜你在找的iOS相关文章