xcode 使用 Objective C 将 POST 发送到 Web 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12044484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:16:55  来源:igfitidea点击:

Sending POST to a web server using Objective C

objective-ciosxcodepostwebserver

提问by Ben T.

I have a pretty basic internal iOS app that I want to send a POST to a web-server. You basically have a bunch of buttons, and depending on what button you press, it sends a pre-defined "message" to the web-server.

我有一个非常基本的内部 iOS 应用程序,我想将 POST 发送到网络服务器。您基本上有一堆按钮,根据您按下的按钮,它会向网络服务器发送一条预定义的“消息”。

Once the buttons are pressed it takes them to another view and says Thanks for selecting the button that you pressed. I also want a pre-defined message to be sent to a web-server, formatted and then emailed to a static email address.

按下按钮后,它会将它们带到另一个视图并说感谢您选择您按下的按钮。我还希望将预定义的消息发送到网络服务器,进行格式化,然后通过电子邮件发送到静态电子邮件地址。

This is what I have so far.. I'm just trying to figure out the best way to send the POST. Is the way I have setup the best way to do it? Or is there smarter way to do this?

到目前为止,这就是我所拥有的。我只是想找出发送 POST 的最佳方式。我的设置方式是最好的方式吗?或者有更聪明的方法来做到这一点?

Sorry if it's messy and un-organized.. I'm very new to iOS development.

对不起,如果它是凌乱和无组织的。我对 iOS 开发很陌生。

@interface DrinkViewController () {
NSString *buttonlabel;
NSString *urlEncodeUsingEncoding;
}
@end

@implementation DrinkViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

-(IBAction)selectButton:(id)sender{
    NSLog(@"Button Pressed:%d",((UIButton *)sender).tag);
    NSString *dvalue;
    switch (((UIButton *)sender).tag) {
        case 1:
            dvalue = @"Button 1";
            break;
        case 2:
            dvalue = @"Button 2";
            break;
        case 3:
            dvalue = @"Button 3";
            break;
        case 4:
            dvalue = @"Button 4";
            break;
        case 5:
            dvalue = @"Button 5";
            break;
        case 6:
            dvalue = @"Button 6";
            break;
        case 7:
            dvalue = @"Button 7";
            break;

    }
    buttonlabel = dvalue;

    [self performSegueWithIdentifier:@"selectionTransition" sender:sender];


    NSData *postData = [buttonlabel dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request =  [NSMutableURLRequest alloc];
                                    [request setURL:[NSURL URLWithString:@"http://www.abc.com/form.php"]];
                                    [request setHTTPMethod:@"POST"];
                                    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                                    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                                    [request setHTTPBody:postData];
    NSLog(@"POST: %@ sent to %@", buttonlabel, request);
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"selectionTransition"]) {

        NSLog(@"%@", buttonlabel);
        // Get destination view
        DetailViewController *vc = [segue destinationViewController];

        // Pass the information to your destination view
        [vc setLabelValue:buttonlabel];
    }
}

@end

回答by J2theC

Here's what you need to use: NSURLRequest, NSURLConnection, NSURLResponse, NSURL. You might use another library, but i would recommend you to try to understand how these classes work (since you are new to this).

以下是您需要使用的:NSURLRequest、NSURLConnection、NSURLResponse、NSURL。您可能会使用另一个库,但我建议您尝试了解这些类的工作原理(因为您是新手)。

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsurlconnection_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsurlconnection_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLResponse_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLResponse_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html

Here's how it works: You use the server url, create a NSURLRequest, assign the proper HTTP method(POST, GET, etc) and other necessary request headers, then you would call on NSURLConnection to get the response and the server data.

这是它的工作原理:您使用服务器 url,创建一个 NSURLRequest,分配正确的 HTTP 方法(POST、GET 等)和其他必要的请求标头,然后您将调用 NSURLConnection 以获取响应和服务器数据。

回答by Thawe

I am by far no expert, but I do make network calls in my code. I chose MKNetworkKitto replace my sorry network code.

我目前还不是专家,但我确实在我的代码中进行了网络调用。我选择了MKNetworkKit来替换我抱歉的网络代码。

Here is an example of how you may use it in your project:

以下是如何在项目中使用它的示例:

- (void)myFunctionToSendDataToTheServer
{
    /*
     *  So here is a basic idea of how you could quickly use MKNetworkKit.
     *  the [op addData:postData forKey:@"postDataKey"]; call is where you're
     *  add that post data to the request body.
     */
    NSString *someVariableYouWantPosted;
    NSData *postData = [someVariableYouWantPosted dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"abc.com"];

    MKNetworkOperation *op = [engine operationWithPath:@"/form.php"];
    [op addData:postData forKey:@"postDataKey"];

    /*
     *  If you're not familiar with blocks then this "onCompletion^" might look weird.
     *  Inside of the curly braces will get called when the request is done.
     */

    [op onCompletion:^(MKNetworkOperation *completedOperation) {
        NSLog(@"Successful response from server: %@", [completedOperation responseString]);

        /*
         *  There are also some nice helper methods for extracting the response data in a different form
         *  [completedOperation responseJSON];
         *  [completedOperation responseImage];
         *  [completedOperation responseData];
         */

    } onError:^(NSError *error) {
        if ([error code] == kCFURLErrorNotConnectedToInternet) {
            /*
             *  Maybe retry? 
             *  This network kit also comes with a "freezable" property on the MKNetworkOperation.
             *  If you set that to YES then you don't need to worry about internet connectivity,
             *  the kit will try to send later when it reconnects.
             */
        }
        else {
            /*
             *  You'll have your work cut out for you here. Sourcing the problem can be difficult.
             *  Simply an alert message or loggin the NSError to find out where you went wrong.
             */
        }

    }];

    /*
     * Don't forget to call "enqueueOperation:".
     *  This actually gets the request going and sends it off to the server.
     */

    [engine enqueueOperation:op];
}

Let me know if you have any other questions regarding this topic or if I wasn't clear.

如果您对此主题有任何其他问题,或者我不清楚,请告诉我。

回答by ezekielDFM

My suggestion would be to use a 3rd party library. It will simplify the process for your considerably and save you a lot of time. I usually use the AFNetworking library.

我的建议是使用 3rd 方库。它将大大简化您的流程并为您节省大量时间。我通常使用 AFNetworking 库。

https://github.com/AFNetworking/AFNetworking

https://github.com/AFNetworking/AFNetworking

There is a POST example here:

这里有一个 POST 示例:

http://www.6foot3foot.com/developer-journal/afnetworking-php

http://www.6foot3foot.com/developer-journal/afnetworking-php

回答by LJ Wilson

Check out this post. I wrote a NetworkClient class that uses AFNetworking (my fav 3rd party library). This is pretty flexible and feel free to modify it to fit your needs.

看看这篇文章。我编写了一个使用 AFNetworking(我最喜欢的第 3 方库)的 NetworkClient 类。这是非常灵活的,可以随意修改它以满足您的需求。