使用NSURLRequest将数据POST到服务器时出现问题 [英] Problem using NSURLRequest to POST data to server

查看:115
本文介绍了使用NSURLRequest将数据POST到服务器时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个 NSURLRequest 将我的数据在iPhone应用程序中发布到服务器以继续PHP脚本。我的PHP脚本看起来像这样。

I create an NSURLRequest to post my data in the iPhone application to a server to proceed the PHP script. My PHP script is look like this.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];

    $link = mysql_connect("localhost", "fffasfdas","Nfdsafafs") or die ("Unable to connect to database.");
    mysql_select_db("muradsbi_mydatabase") or die ("Unable to select database.");

    $sqlstatement= "INSERT INTO dbname (name,email) VALUES ('$name','$email')";
    $newquery = mysql_query($sqlstatement, $link);
    echo 'thanks for your register';
?>

和我的 NSURLRequst

NSString *myRequestString = @"&name=Hello%20World&email=Ohai2u";
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://www.google.com/"]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: myRequestData];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];

但是,此网站无法从此应用程序获取数据并将其保存到数据库,我知道它连接成功,因为我的应用程序能够从服务器获取响应数据。我不知道我的变量名是否以错误的方式声明或其他问题。

However, this site is unable to get the data from this application and save it to the database, but I know it was connected succussfully because my application is able to get the response data from the server. I don't know whether my variable name is declared in the wrong way or others issues. How can I fix it?

推荐答案

您应该删除前面的& myRequestString ,问题很可能是没有发送正确的 content-type 头。尝试添加对

You should remove the leading & in myRequestString and the problem is likely that the correct content-type header is not being sent. Try adding a call to

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

您也不应该传递 nil ,因此您可以看到客户的想法。

You should also not pass nil for error, so you can see what the client thinks is going on.

不相关,但您的PHP代码可以打开 SQL注入攻击

Unrelated, but your PHP code is open to SQL injection attacks.

这篇关于使用NSURLRequest将数据POST到服务器时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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