嘿,
我的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>已经谢谢了
发布于 2011-03-21 21:55:01
我有时遇到同样的问题,解决方案是将以下内容添加到请求中:
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];发布于 2011-03-22 00:38:36
问题的一个可能根源可能是,在代码中,您在将值分配给msgLength变量之前设置了Content-Length标头。由于nil对象上的ob Obj-C方法返回nil ( nil为0),因此您将Content-Lenght设置为0。尝试移动这条线
NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];在此之前
[urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];发布于 2011-03-21 22:04:37
我建议你尝试一下ASIHTTPRequest Library,它不仅可以像使用ASIFormDataRequest一样简单地处理http请求,而且还易于异步处理。
https://stackoverflow.com/questions/5378411
复制相似问题