如何使用Objective-C将HTTP POST请求发送到PHP服务 [英] How to send HTTP POST request to PHP service with Objective-C

查看:115
本文介绍了如何使用Objective-C将HTTP POST请求发送到PHP服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

由于你没有提及您想要使用哪种体型,此示例将向您展示如何发布multipart / form-data请求。

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

如果正文是 application / x-www-form -urlencoded 你应该改变这样的Content-Type值。

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"];

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

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

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

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

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

这篇关于如何使用Objective-C将HTTP POST请求发送到PHP服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆