2

嘻嘻,

我的 NSURLRequest HTTP POST 出现问题,我无法找出问题所在。

这是我的服务器端 php:

<html>
<head>
</head>
<body>
    <?php 
        if (! isset($_POST['sometext'])) {
            echo "NOT SET";
        } else {
            echo $_POST['sometext'];
        }
    ?>
</body></html>

这是我发布数据的目标 c 代码:

NSString *urlString = @"http://localhost:8888/postpage";
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];

[url release];


    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    NSString *postString = @"sometext=Hello&language=en";
    NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];
    [urlRequest setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];


NSString *returnString = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);

NSLog 的结果是:

<html>
    <head>
    </head>
    <body>
        NOT SET 
    </body>
</html>

已经谢谢了

4

3 回答 3

4

我有时遇到同样的问题,解决方案是将其添加到请求中:

[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
于 2011-03-21T13:55:00.540 回答
2

问题的一个可能来源可能是在代码中您在将值分配给msgLength变量之前设置了Content-Length标头。因为 nil 对象上的 obj-C 方法返回 nil(并且 nil 为 0),所以您将 Content-Lenght 设置为 0。尝试移动线

NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];

[urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
于 2011-03-21T16:38:35.620 回答
0

我建议您可以尝试ASIHTTPRequest 库,它不仅可以像您的问题一样轻松处理 http 请求,只需使用ASIFormDataRequest,而且还可以轻松进行异步处理。

于 2011-03-21T14:04:36.550 回答