gpt4 book ai didi

ios - 将 JSON 发送到原理图 Ipsum

转载 作者:行者123 更新时间:2023-11-29 02:53:03 24 4
gpt4 key购买 nike

我正在尝试从 http://schematic-ipsum.herokuapp.com/ 中获取一些随机 JSON但我收到了响应代码 400。

这是我正在使用的代码

+ (NSArray *)postData:(NSDictionary *)arguments toServer:(NSString *)urlString
{
NSArray *dataToReturn;

// if urlString is nil, we default it to our server
if(!urlString) urlString = JSON_SERVER;

// of course we need to turn the string into a valid array
NSURL *url = [NSURL URLWithString:urlString];

/*
prepare the post
*/

// we need to catch possible errors
NSError *error;

// turn our arguments into NSData
NSData *postData = [NSJSONSerialization dataWithJSONObject:arguments options:0 error:&error];

// we need the post' length
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

// create the url request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

// here we'll check the server response
NSHTTPURLResponse *response = nil;

// here's our data from the server
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if ([response statusCode] >=200 && [response statusCode] <300)
{
// all good, let's see what we've got
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"Response ==> %@", responseData);

// parse the response into a friendly format
dataToReturn = [[NSArray alloc] initWithArray:[self returnJSONFromData:urlData]];
} else {
// somethin went wrong
NSLog(@"Response code: %ld", (long)[response statusCode]);
// check if it's our fault
if (error) {
NSLog(@"Server error: %@", [error localizedDescription]);
}
}

// return our formatted array or nil
return dataToReturn;
}

+ (NSArray *)returnJSONFromData:(NSData *)urlData
{
NSArray *dataToReturn;

NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: urlData options: NSJSONReadingMutableContainers error: &e];

if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", [e localizedDescription]);
dataToReturn = @[e];
} else {
dataToReturn = [[NSArray alloc] initWithArray:jsonArray];
NSLog(@"data from json: %@", dataToReturn);
}

return dataToReturn;
}

我这样调用它,使用他们网站上的演示 JSON:

NSDictionary *post = @{ @"type": @"object", @"properties": @{ @"id": @{ @"type": @"string", @"ipsum": @"id" }, @"name": @{ @"type": @"string", @"ipsum": @"name" }, @"email": @{ @"type": @"string", @"format": @"email" } }};
[RetrieveDataFromServer postData:post toServer:@"http://schematic-ipsum.herokuapp.com/"];

最佳答案

您需要遵守服务器采用的“表单数据”语法。为此,您可以使用 Google Chrome 浏览器的“检查元素”,选择“网络”选项卡,然后发出请求,您将看到:

enter image description here

看看“表单数据”部分,你会发现你的问题,这是因为你没有将正确的结构传递给服务器,所以服务器不理解。 enter image description here

enter image description here

我采用了服务器的默认参数:

{
"type": "object",
"properties": {
"id": {
"type": "string",
"ipsum": "id"
},
"name": {
"type": "string",
"ipsum": "name"
},
"email": {
"type": "string",
"format": "email"
},
"bio": {
"type": "string",
"ipsum": "sentence"
},
"age": {
"type": "integer"
},
"avatar": {
"type": "string",
"ipsum": "small image"
}
}
}

所以数据的结构必须是这样的:

type:object
properties[id][type]:string
properties[id][ipsum]:id
properties[name][type]:string
properties[name][ipsum]:name
properties[email][type]:string
properties[email][format]:email
properties[bio][type]:string
properties[bio][ipsum]:sentence
properties[age][type]:integer
properties[avatar][type]:string
properties[avatar][ipsum]:small image

在发送到服务器之前不要忘记用百分比编码,否则你会再次失败。我尝试实现一种获取字典并返回格式化表单数据的方法,它在这种情况下工作正常,但我不确定在更一般的上下文中。我会把它贴在这里供你引用,真的很乱,对此很抱歉,但我没有足够的时间发表评论。

- (NSString *)formatFormData:(NSDictionary *)dictionary
{
NSMutableArray *arrayPrefix = [NSMutableArray array];
NSMutableArray *arrayResult = [NSMutableArray array];
[self structureString:dictionary arrayPrefix:arrayPrefix arrayResult:arrayResult];
return [arrayResult componentsJoinedByString:@"&"];;
}

- (void)structureString:(NSDictionary *)dictionay arrayPrefix:(NSMutableArray *)arrayPrefix arrayResult:(NSMutableArray *)arrayResult
{
for(NSString *key in dictionay.allKeys)
{
NSObject *obj = [dictionay objectForKey:key];
if([obj isKindOfClass:[NSDictionary class]])
{
[arrayPrefix addObject:key];
[self structureString:(NSDictionary *)obj arrayPrefix:arrayPrefix arrayResult:arrayResult];
}
else
{
NSMutableString *string = [[NSMutableString alloc] initWithString:@""];
for(int i = 0; i < arrayPrefix.count; i++)
{
NSString *eachPrefix = arrayPrefix[i];
if(i == 0)
{
[string appendString:eachPrefix];
}
else
{
[string appendString:[NSString stringWithFormat:@"[%@]", eachPrefix]];
}

}
if(arrayResult.count == 0)
{
[string appendString:[NSString stringWithFormat:@"%@=%@", key, obj]];
}
else
{
[string appendString:[NSString stringWithFormat:@"[%@]=%@", key, obj]];
}

[arrayResult addObject:string];
}
}
}

在您当前的方法中,添加以下行:

- (NSArray *)postData:(NSDictionary *)arguments toServer:(NSString *)urlString
{
// omitted

// turn our arguments into NSData
NSData *postData = [NSJSONSerialization dataWithJSONObject:arguments options:0 error:&error];
NSString *stringTemp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
stringTemp = [self formatFormData:arguments];
// encode form date before sending to server
stringTemp = [stringTemp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
postData = [stringTemp dataUsingEncoding:NSUTF8StringEncoding];

// omitted
}

关于ios - 将 JSON 发送到原理图 Ipsum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24256949/

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