Simple http post example in Objective-C?

后端 未结 8 1462
谎友^
谎友^ 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条回答
  • 2020-11-28 02:01

    From Apple's Official Website :

    // In body data for the 'application/x-www-form-urlencoded' content type,
    // form fields are separated by an ampersand. Note the absence of a
    // leading ampersand.
    NSString *bodyData = @"name=Jane+Doe&address=123+Main+St";
    
    NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]];
    
    // Set the request's content type to application/x-www-form-urlencoded
    [postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    // Designate the request a POST request and specify its body data
    [postRequest setHTTPMethod:@"POST"];
    [postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
    
    // Initialize the NSURLConnection and proceed as described in
    // Retrieving the Contents of a URL
    

    From : code with chris

        // Create the request.
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
    
    // Specify that it will be a POST request
    request.HTTPMethod = @"POST";
    
    // This is how we set header fields
    [request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    // Convert your data and set your request's HTTPBody property
    NSString *stringData = @"some data";
    NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBodyData;
    
    // Create url connection and fire request
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    0 讨论(0)
  • 2020-11-28 02:02

    ASIHTTPRequest makes network communication really easy

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request addPostValue:@"Ben" forKey:@"names"];
    [request addPostValue:@"George" forKey:@"names"];
    [request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"];
    [request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"];
    
    0 讨论(0)
  • 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];
    }
    
    0 讨论(0)
  • 2020-11-28 02:08

    Here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.

    //POST DATA
    NSString *theBody = [NSString stringWithFormat:@"parameter=%@",YOUR_VAR_HERE];
    NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    //URL CONFIG
    NSString *serverURL = @"https://your-website-here.com";
    NSString *downloadUrl = [NSString stringWithFormat:@"%@/your-friendly-url-here/json",serverURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
    //POST DATA SETUP
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:bodyData];
    //DEBUG MESSAGE
    NSLog(@"Trying to call ws %@",downloadUrl);
    //EXEC CALL
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if (error) {
            NSLog(@"Download Error:%@",error.description);
        }
        if (data) {
    
            //
            // THIS CODE IS FOR PRINTING THE RESPONSE
            //
            NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
            NSLog(@"Response:%@",returnString);
    
            //PARSE JSON RESPONSE
            NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
                                                                          options:0
                                                                            error:NULL];
    
            if ( json_response ) {
                if ( [json_response isKindOfClass:[NSDictionary class]] ) {
                    // do dictionary things
                    for ( NSString *key in [json_response allKeys] ) {
                        NSLog(@"%@: %@", key, json_response[key]);
                    }
                }
                else if ( [json_response isKindOfClass:[NSArray class]] ) {
                    NSLog(@"%@",json_response);
                }
            }
            else {
                NSLog(@"Error serializing JSON: %@", error);
                NSLog(@"RAW RESPONSE: %@",data);
                NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
                NSLog(@"Response:%@",returnString2);
            }
        }
    }];
    

    Hope this helps!

    0 讨论(0)
  • 2020-11-28 02:15

    Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )

    0 讨论(0)
  • 2020-11-28 02:21
     NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
    [contentDictionary setValue:@"name" forKey:@"email"];
    [contentDictionary setValue:@"name" forKey:@"username"];
    [contentDictionary setValue:@"name" forKey:@"password"];
    [contentDictionary setValue:@"name" forKey:@"firstName"];
    [contentDictionary setValue:@"name" forKey:@"lastName"];
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:data
                                              encoding:NSUTF8StringEncoding];
    NSLog(@"%@",jsonStr);
    
    NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
       [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    
    [request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
    
    0 讨论(0)
提交回复
热议问题