gpt4 book ai didi

ios - 使用 iOS 发送 JSON 请求

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:07:23 25 4
gpt4 key购买 nike

我在尝试使用 iOS 应用程序发送 JSON 请求时遇到问题。我必须发送这样的内容:

http://url/User/Create/{"newsletter" : 1,"password" : "sdsd", ...}

但是在应用程序上执行此操作时请求无效:

 NSURL   *url = [NSURL URLWithString:@"http://url/User/Create/"];
NSData *jsonData;

NSDictionary *dic = @{
@"login" : @"sdsd",
@"password" : @"sdsd",
@"newsletter" : @1,
@"firstname" : @"sdsd",
@"lastname" : @"sdsd",
@"email" : @"sdsd@hotmail.fr"};
jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: jsonData];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];

NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];

如何以有效格式发送请求?

最佳答案

-(void)tryThis  
{
NSString *a=@"{'login' : 'sdsd', 'password' : 'sdsd', 'newsletter' : 1, 'firstname' : 'sdsd', 'lastname' : 'sdsd', 'email' : 'sdsd@hotmail.fr'}";
a= [a stringByReplacingOccurrencesOfString:@"'" withString:@"\"" options:NSCaseInsensitiveSearch range:NSMakeRange (0, [a length])];
NSData* postData= [a dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https:***********your url"]];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData1 encoding:NSUTF8StringEncoding];
}

关于ios - 使用 iOS 发送 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22038551/

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