gpt4 book ai didi

ios - NSData返回0个字节

转载 作者:行者123 更新时间:2023-12-01 20:21:24 34 4
gpt4 key购买 nike

我正在尝试做一个简单的POST请求。但是,在Chrome和iOS模拟器中的POSTMAN插件中,结果似乎有所不同。

这是POSTMAN的快照:

enter image description here

enter image description here

如您所见,我在重新调整中获得了JSON数据。

这是我执行POST请求的代码:

    NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:kPostURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];


NSString *params =[[NSString alloc] initWithFormat:@"fname=%@&lname=%@&email=%@&password=%@&switchid=%d&didflag=%@",fname,lname,email,pass,switchid,flag];

[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

NSLog(@"response is %@",response);
NSLog(@"erros is %@",error);

NSMutableDictionary * innerJson = [NSJSONSerialization
JSONObjectWithData:data options:kNilOptions error:&error
];
NSLog(@"JSON data is %@",innerJson);

}];

[postDataTask resume];

当我尝试在调试器中打印值时,我得到
JSON作为 nullNSData作为 0 bytes。但是我得到了成功的 status code as 200

这是我得到的答复:
      { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 0;
"Content-Type" = "text/html";
Date = "Thu, 25 Feb 2016 02:04:02 GMT";
"Keep-Alive" = "timeout=5";
Server = "Apache/2.4.12";
"X-Powered-By" = "PHP/5.5.30";
} }

为什么我将NSData设为0字节?

最佳答案

在chrome的请求中,您将参数作为URL参数。在ObjC版本中,您将添加参数作为帖子的一部分。

而不是将参数添加为主体的一部分:

[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

将其添加为查询的一部分:
NSURL *url = [NSURL URLWithString:[kPostURL stringByAppendingFormat:@"?%@", params]];

关于ios - NSData返回0个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617015/

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