Objective C Post Request

时间:2015-11-25 13:59:45

标签: php ios objective-c

我使用post方法编写了一个Php代码,当前放在服务器上,当我向服务器发出请求时,响应为空。

代码如下:

/json responce array
$response = array("error" => FALSE);

if(isset($_POST['device_id']) && isset($_POST['country'])){

    $device = $_POST['device_id'];
    $country = $_POST['country'];

    $sql = "SELECT country_id FROM newsletter_country WHERE country_name = '$country';";
    $res = mysql_query($sql) or die(mysql_error());
    $row = mysql_fetch_array($res) or die(mysql_error());
    $c_id = $row['country_id'];

    $sql = "SELECT * FROM users WHERE device = '$device';";
    $res = mysql_query($sql) or die(mysql_error());
    if(mysql_num_rows($res) > 0){

        $response["error"] = TRUE;
        $response["error_msg"] = "User already existed with " . $device;
    }
    else{

        $qry = "INSERT INTO users(country_id,country,device,user_status) VALUES($c_id,'$country','$device','NEW');";
        $res = mysql_query($qry) or die(mysql_error());
        if($res){
        $response["error"] = FALSE;
        $response["user"]["country"] = $country;
        $response["user"]["device_id"]=$device;
        $response["error_msg"] = "User Successfully Registered with ".$device;
        }
        else{
            $response["error"] = TRUE;
            $response["error_message"] = "Unknow Error occur try again later";
        }
    }

    echo json_encode($response);
}else{

        $response["error"] = TRUE;
        $response["error_msg"] = "Unable to Register. Parameters are not complete";
        echo json_encode($response);

相同的代码适用于android,请对Objective C代码进行审核:

NSString *device_id = @"test@gmail.com";
NSString *country = @"Mexico";

NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:/linkhere/adduser.php"]];
[request setHTTPMethod:@"POST"];

NSString *post =[[NSString alloc] initWithFormat:@"device_id=%@&country=%@",device_id,country];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];

NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];


 if (responseData != nil){
    NSMutableArray* json = [NSJSONSerialization JSONObjectWithData:responseData //1
                                                           options:0
                                                             error:&err];

    NSLog(@"%@",json);

}

感谢您的审核和帮助。

1 个答案:

答案 0 :(得分:0)

尝试使用NSURLSession,因为不推荐使用NSURLConnection。这是第一步。