Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

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

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:@"
--%@
", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[[NSString stringWithFormat:@"%@=%@", @"name", @"John"] dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[[NSString stringWithFormat:@"
--%@
", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[[NSString stringWithFormat:@"%@=%@", @"password", @"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[[NSString stringWithFormat:@"
--%@
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...