gpt4 book ai didi

ios - Objective-C HTTP POST 请求

转载 作者:可可西里 更新时间:2023-11-01 04:10:38 25 4
gpt4 key购买 nike

我正在使用一个使用 HTTP 的 SMS 网关。我使用有关 stackoverflow 等的教程和问题创建了一个请求,但出了点问题。当我手动输入 URL 时,我可以毫无问题地使用网关,但我无法以编程方式执行此操作,所以我认为我的代码可能不正确。感谢任何帮助!

NSString *post = [NSString stringWithFormat:@"user=%@&password=%@&api_id=%@&to=%@&text=%@",_username,_password,_apiID,[_numbers componentsJoinedByString:@","],_txtMsg.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://api.mySmsGateWay.com/http/sendmsg"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;

NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
NSLog(@"Error getting, HTTP status code %i", [responseCode statusCode]);
}

NSLog (@"%@", [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding]);

最佳答案

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://api.mySmsGateWay.com/http/sendmsg"]];

NSString *userUpdate =[NSString stringWithFormat:@"user=%@&password=%@&api_id=%@&to=%@&text=%@",_username,_password,_apiID,[_numbers componentsJoinedByString:@","],_txtMsg.text, nil];

//create the Method "GET" or "POST"
[urlRequest setHTTPMethod:@"POST"];

//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];

//Apply the data to the body
[urlRequest setHTTPBody:data1];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(@"The response is - %@",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:@"success"] integerValue];
if(success == 1)
{
NSLog(@"Login SUCCESS");
}
else
{
NSLog(@"Login FAILURE");
}
}
else
{
NSLog(@"Error");
}
}];
[dataTask resume];

关于ios - Objective-C HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39841045/

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