简体   繁体   English

Objective-C POST请求不发送数据

[英]Objective-C POST request not sending data

I have a method that should post some data to a PHP file: 我有一个方法应该将一些数据发布到PHP文件:

-(void)submitForm {
    NSLog(@"name=%@", formName.text); // returns correct value

    NSString *post = [NSString stringWithFormat:@"name=%@&", formName.text];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://path/to/file"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSURLResponse *response = NULL;
    NSError *requestError = NULL;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    NSLog(@"%@",responseString);
}

Note: I'm not actually using @"http://path/to/file" . 注意:我实际上并没有使用@"http://path/to/file" I've omitted the URL for privacy. 我已经省略了隐私网址。

I believe it's connecting to the PHP script correctly, since I'm receiving the response I expect. 我相信它正确地连接到PHP脚本,因为我收到了我期望的响应。 The problem is that if I echo out $name , I get an empty string. 问题是,如果我echo $name ,我会得到一个空字符串。 Here's the script: 这是脚本:

<?php
include("config.php"); // Handles DB connection
$name = mysql_escape_string($_POST["name"]);
mysql_query("insert into objects(name) values('$name')") or die(mysql_error());
echo $name; // returns empty string

All I expect is some sort of syntax/logic error in the Obj-C code, but I can't spot it. 我所期望的是Obj-C代码中的某种语法/逻辑错误,但我无法发现它。

I've got a feeling that your request is missing some mandatory data, a boundary and content-type, which might lead to your POST request being half complete. 我有一种感觉,你的请求缺少一些强制数据,边界和内容类型,这可能导致你的POST请求完成一半。

I'll show you what I've done for uploading an HTML file to a webserver and then explain underneath. 我将向您展示我为将HTML文件上传到网络服务器所做的工作,然后在下面解释。

Objective-C Objective-C的

NSString* str = formName.text;
NSData* theData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = @"http://whereyouarepostingto.com";

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];  
[request setURL:[NSURL URLWithString:urlString]];  
[request setHTTPMethod:@"POST"];  

NSString *boundary = @"---------------------------14737809831466499882746641449";  
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];  

[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];  

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary]   dataUsingEncoding:NSUTF8StringEncoding]];  
[body appendData:[[NSString stringWithString:[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"file\"; filename=\"%@.html\"\r\n", self.fileName]] dataUsingEncoding:NSUTF8StringEncoding]];  
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:theData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];  
[request setHTTPBody:body];  

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 

NSLog(@"%@", returnString);

PHP PHP

   <?php

    echo "Connection made to server";

    move_uploaded_file($_FILES["file"][tmp_name], "uploads/" . $_FILES["file"]["name"]);  

    ?>

You'll need to change a few things around to fit your SQL insert and strip out my file stuff, but it's a start. 你需要改变一些东西来适应你的SQL插入并删除我的文件内容,但这是一个开始。

This is the part I think you're missing. 这是我认为你错过的部分。

NSString *boundary = @"---------------------------14737809831466499882746641449";  
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

The boundary can be a series of random numbers, but it has to exist. 边界可以是一系列随机数,但它必须存在。

Also, watch out when constructing the body of the request, especially the slashes. 另外,在构造请求的主体时要小心,特别是斜杠。 Make sure you escape any " ". 确保你逃脱任何“”。

Man you are not encoding all your Variables. 你没有编码所有变量的人。 You should make URL-Encode for your variable. 您应该为变量创建URL-Encode。 The sample of Encoding function you can find here: 你可以在这里找到编码功能的样本:

+(NSString *)urlEncode:(NSString *)unencodedString{
    return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                            (CFStringRef)[NSHelper string:unencodedString],
                                                            NULL,
                                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                            kCFStringEncodingUTF8 );
}

And by the way remove '&' character in the end of POST string. 并顺便删除POST字符串末尾的'&'字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM