我尝试使用afnetworking从iPhone模拟器发送帖子数据。我试图检查php页面是否接收到数据。但是很遗憾,它没有收到任何发布数据。我尝试使用var_dump($ _ POST),但它返回一个空数组。这是我的代码:

用于将数据发送到PHP的iOS代码(ViewController.h):

- (IBAction)onSend:(id)sender {

    NSURL *url = [NSURL URLWithString:@"http://localhost/sample/"];
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:firstnameTextField.text, @"firstname", lastnameTextField.text, @"lastname",nil];

    [client postPath:@"sample.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        UIAlertView *succesAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Post Success" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [succesAlert show];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}


PHP代码(sample.php):

<?php
    if(isset($_POST["firstname"]) && isset($_POST["lastname"]))
    {
        $fname = $_POST["firstname"];
        $lname = $_POST["lastname"];
        echo $fname."<br/>";
        echo $lname;
    }

    echo var_dump($_POST);
?>

最佳答案

我用这样的东西:

// Your http url

NSURL* url = @"<your web url>";

AFHTTPClient* client = [[AFHTTPClient alloc]initWithBaseURL:url];



// create request
NSMutableURLRequest *request=[NSMutableURLRequest
                              requestWithURL:[NSURL URLWithString:strUrl]
                              cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
                              timeoutInterval:60.f];

// set http method as POST
[request setHTTPMethod:@"POST"];

// TODO: set your params for post, convert them to post data and set to requesr
// NSMutableDictionary* authParams = @{ "param1" : @"val1", @"param2" : @"val2"}
// [request setHTTPBody:postData]

// sample file upload combined with post action
request = [client multipartFormRequestWithBaseRequest:request parameters:authParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    // Important!! : file path MUST BE real file path (so -> "file://localhost/.../../file.txt") so i use [NSURL fileURLWithPath:]
    NSError* err;
    [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePathToUpload] name:[fileInfo objectForKey:@"fileName"] error:&err];

}];

AFHTTPRequestOperation *operationX = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[operationX setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    // call to external completion block

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    // call to external failure block

}];

// run operation
[yourOperationQueue addOperation:operationX];


// =============

//implementing in AFHTTPClient ( for upload case , to reuse you own request)

- (NSMutableURLRequest *)multipartFormRequestWithBaseRequest:(NSMutableURLRequest*)request
                                         parameters:(NSDictionary *)parameters
                          constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
{

__block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc]   initWithURLRequest:request stringEncoding:self.stringEncoding];

if (parameters) {
    for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
        NSData *data = nil;
        if ([pair.value isKindOfClass:[NSData class]]) {
            data = pair.value;
        } else if ([pair.value isEqual:[NSNull null]]) {
            data = [NSData data];
        } else {
            data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
        }

        if (data) {
            [formData appendPartWithFormData:data name:[pair.field description]];
        }
    }
}

if (block) {
    block(formData);
}

return [formData requestByFinalizingMultipartFormData];


}

08-04 13:59