如何使用Objective-C将HTTP POST请求发送到PHP服务

时间:2014-07-28 04:04:13

标签: objective-c http-post nsurlconnection nsmutableurlrequest

我试图发布到PHP并获得响应。 php文件有一个echo“hello”,它应该只打印你好。我正在尝试测试发布是否有效,但在我的错误日志中,NSlog没有显示任何内容:

@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 个答案:

答案 0 :(得分:1)

由于您未提及要使用的体型类型,因此本示例向您展示了如何发布multipart / form-data请求。

-(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);
        }
    }];
}

如果正文为application/x-www-form-urlencoded,则应更改内容类型值。

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

并用此替换// form-data块。

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

@"John"@"myPassword"必须进行网址编码。