How to send HTTP POST request to PHP service with Objective-C

試著忘記壹切 提交于 2019-12-11 14:27:05

问题


Im trying to post to php and get the response. The php file has an echo "hello" which should just print hello. I'm trying to test to see if posting is working but in my error log the NSlog doesn't display anything:

@interface ViewController ()

@end

@implementation ViewController
@synthesize email, password,receivedData;

-(IBAction)Login:(id)sender{

    // Create the request.
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://grouporder.site90.net/test.php"]];

    // 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 = [NSString stringWithFormat:@"%@", email];

    NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBodyData;

    // Create url connection and fire request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
     [receivedData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    //initialize convert the received data to string with UTF8 encoding
    NSString *htmlSTR = [[NSString alloc] initWithData:receivedData
                                              encoding:NSUTF8StringEncoding];
    NSLog(@"%@" , htmlSTR);
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
     NSLog(@"%@" , error);
}

回答1:


Since you did not mention about what kind of body type you want to use this example shows you how to post multipart/form-data request.

-(NSString *)generateRandomBoundryString {
    CFUUIDRef UUID = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef UUIDString = CFUUIDCreateString(kCFAllocatorDefault,UUID);
    NSString *aNSString = (__bridge NSString *)UUIDString;
    CFRelease(UUID);
    CFRelease(UUIDString);
    return aNSString;
}

-(IBAction)Login:(id)sender {
    NSString *bndry = [self generateRandomBoundryString]; 
    NSString *contentType = [[NSString alloc] initWithString:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", bndry]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://grouporder.site90.net/test.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue: contentType forHTTPHeaderField:@"Content-Type"];

    //form-data block
     NSMutableData *requestBody = [NSMutableData data];
    [requestBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[[NSString stringWithFormat:@"%@=%@", @"name", @"John"] dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[[NSString stringWithFormat:@"%@=%@", @"password", @"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:requestBody];
    //form-data block

    // NSURLConnection Asynchronous Block
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rspreportStatus, NSData *datareportStatus, NSError *e)
    {
        if (e == nil)
        {
            // If all ok you can processes response data here.
        }
        else {
            NSLog(@"%@", e.localizedDescription);
        }
    }];
}

If body is application/x-www-form-urlencoded you should change Content-Type value like this.

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

and replace //form-data block block with this.

[requestBody appendData:[[NSString stringWithFormat:@"name=%@&password=%@", @"John", @"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];

@"John" and @"myPassword" has to be URL encoded.



来源:https://stackoverflow.com/questions/24988261/how-to-send-http-post-request-to-php-service-with-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!