OStack程序员社区-中国程序员成长平台

标题: ios - 如何使用 AFNetworking 在 iOS objective-c 中发出此帖子请求 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 00:21
标题: ios - 如何使用 AFNetworking 在 iOS objective-c 中发出此帖子请求

我需要从 twilio documentation 发出与此等效的 POST 请求在 iOS 中发送短信

curl -XPOST https://api.twilio.com/2010-04-01/Accounts/AC5ef8732a3c49700934481addd5ce1659/Messages.json \
-d "Body=Jenny%20please%3F%21%20I%20love%20you%20<3" \
-d "To=%2B15558675309" \
-d "From=%2B14158141829" \
-u 'AC5ef8732a3c49700934481addd5ce1659:{AuthToken}'

这就是我所拥有的:

NSString *kTwilioSID = @"AC5ef8732a3c49700934481addd5ce1659";
NSString *kTwilioSecret = @"SECRET";
NSString *kFromNumber = @"+14158141829";
NSString *kToNumber = @"+15558675309";
NSString *kMessage = @"Jenny please?! I love you <3";


NSString *twilioURL = [NSString stringWithFormat"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/Messages.json", kTwilioSID, kTwilioSecret, kTwilioSID];
NSDictionary *params = @ {@"account" :kTwilioSID, @"from":kFromNumber, @"to":kToNumber, @"body":kMessage };

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:twilioURL parameters:params
      success:^(AFHTTPRequestOperation *operation, id responseObject)
 {
     NSLog(@"Success: %@", responseObject);
 }
      failure:
 ^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"Error: %@", error);
 }];

失败并出现错误“请求失败:错误请求 (400)”,并且短信也未发送 我该如何解决这个问题?



Best Answer-推荐答案


我建议你不要使用

[manager POST:twilioURL parameters:params ....

这个方法对我不起作用。相反,这里有一个有效的代码示例:

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat"%@", @"http://myurl/actionToperform"]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//1
[request setHTTPMethod"OST"];
[request setValue"application/json" forHTTPHeaderField"Content-Type"];

NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat"{ \"name\" : \"%@\", \"polygon\" : [%@]}",[alertView textFieldAtIndex:0].text, concatCoord] dataUsingEncoding:NSUTF8StringEncoding]];

//post
[request setHTTPBody:postBody];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    //Do things if succesfull
    NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //Do things when you've got an error
    NSLog(@"error: %@", error);
}];

[operation start];

请注意,我在此代码中使用 JSON 来格式化我的参数 (1)。

祝你好运。

关于ios - 如何使用 AFNetworking 在 iOS objective-c 中发出此帖子请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25153554/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4