gpt4 book ai didi

ios - 在 HTTPBody 中设置一个 NSDictionary 并使用 POST 方法发送

转载 作者:可可西里 更新时间:2023-11-01 03:41:22 26 4
gpt4 key购买 nike

我想用 POST 方法调用网络服务。我需要发布带有 URL 的字典。我的网络服务参数如下:

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)
}

以下是我的要求:

    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];

但是我收到以下错误:

服务器拒绝了此请求,因为请求实体的格式不受所请求方法所请求资源的支持

最佳答案

请找到以下将数据发布到网络服务的代码。请注意,这是我在我的一个应用程序中使用的示例。

//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 - 在 HTTPBody 中设置一个 NSDictionary 并使用 POST 方法发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22033921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com