Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

iphone - Problem using NSURLRequest to POST data to server

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';
?>

and my NSURLRequst is created like below.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"];

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...