Simple http post example in Objective-C?

后端 未结 8 1484
谎友^
谎友^ 2020-11-28 01:32

I have a php webpage that requires a login (userid & password). I have the user enter the information into the app just fine.. but I need an example on how to do a POST

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 02:05

    You can do using two options:

    Using NSURLConnection:

    NSURL* URL = [NSURL URLWithString:@"http://www.example.com/path"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"POST";
    // Form URL-Encoded Body
    
    NSDictionary* bodyParameters = @{
        @"username": @"reallyrambody",
        @"password": @"123456"
    };
    request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
    
    // Connection
    
    NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
    [connection start];
    
    /*
     * Utils: Add this section before your class implementation
     */
    
    /**
     This creates a new query parameters string from the given NSDictionary. For
     example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
     string will be @"day=Tuesday&month=January".
     @param queryParameters The input dictionary.
     @return The created parameters string.
    */
    static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
    {
        NSMutableArray* parts = [NSMutableArray array];
        [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
            NSString *part = [NSString stringWithFormat: @"%@=%@",
                [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
                [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
            ];
            [parts addObject:part];
        }];
        return [parts componentsJoinedByString: @"&"];
    }
    
    /**
     Creates a new URL by adding the given query parameters.
     @param URL The input URL.
     @param queryParameters The query parameter dictionary to add.
     @return A new NSURL.
    */
    static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
    {
        NSString* URLString = [NSString stringWithFormat:@"%@?%@",
            [URL absoluteString],
            NSStringFromQueryParameters(queryParameters)
        ];
        return [NSURL URLWithString:URLString];
    }
    

    Using NSURLSession

    - (void)sendRequest:(id)sender
    {
        /* Configure session, choose between:
           * defaultSessionConfiguration
           * ephemeralSessionConfiguration
           * backgroundSessionConfigurationWithIdentifier:
         And set session-wide properties, such as: HTTPAdditionalHeaders,
         HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
         */
        NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    
        /* Create session, and optionally set a NSURLSessionDelegate. */
        NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    
        /* Create the Request:
           Token Duplicate (POST http://www.example.com/path)
         */
    
        NSURL* URL = [NSURL URLWithString:@"http://www.example.com/path"];
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
        request.HTTPMethod = @"POST";
    
        // Form URL-Encoded Body
    
        NSDictionary* bodyParameters = @{
            @"username": @"reallyram",
            @"password": @"123456"
        };
        request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
    
        /* Start a new Task */
        NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (error == nil) {
                // Success
                NSLog(@"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
            }
            else {
                // Failure
                NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
            }
        }];
        [task resume];
    }
    
    /*
     * Utils: Add this section before your class implementation
     */
    
    /**
     This creates a new query parameters string from the given NSDictionary. For
     example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
     string will be @"day=Tuesday&month=January".
     @param queryParameters The input dictionary.
     @return The created parameters string.
    */
    static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
    {
        NSMutableArray* parts = [NSMutableArray array];
        [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
            NSString *part = [NSString stringWithFormat: @"%@=%@",
                [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
                [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
            ];
            [parts addObject:part];
        }];
        return [parts componentsJoinedByString: @"&"];
    }
    
    /**
     Creates a new URL by adding the given query parameters.
     @param URL The input URL.
     @param queryParameters The query parameter dictionary to add.
     @return A new NSURL.
    */
    static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
    {
        NSString* URLString = [NSString stringWithFormat:@"%@?%@",
            [URL absoluteString],
            NSStringFromQueryParameters(queryParameters)
        ];
        return [NSURL URLWithString:URLString];
    }
    

提交回复
热议问题