gpt4 book ai didi

ios - 如何使用 POST 方法快速发送 JSON 数据

转载 作者:行者123 更新时间:2023-11-28 11:12:56 25 4
gpt4 key购买 nike

SWIFT中如何使用POST方式向服务器发送JSON数据

对于 Objective C 我使用这个

NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:validEmailTF.text forKey:@"email"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:@"r=%@",jsonInputString];

NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",forgetPasswordUrl]];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData != nil)
{
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(@"Values =======%@",jsonDict);
}

将此代码转换为 Swift 语言。 enter image description here谢谢

最佳答案

你可以试试这个,也许它会对你有帮助

let request = NSMutableURLRequest(URL: NSURL(string: "Your forgetPasswordUrl")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

let params = ["email":validEmailTF.text] as Dictionary<String, String>

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")})

task.resume()

关于ios - 如何使用 POST 方法快速发送 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33840750/

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