将带有数据的POST请求从c#级别发送到PHP脚本

时间:2014-10-01 13:48:44

标签: c# php request

所以我有一个php脚本(它的名字是wiadomosci.php),代码如下:

<?php
if (isset($_GET['wszystkie'])) //when I'm sending GET with wszystkie? paramets it send back all records in JSON -  it works without any problems
{
$con=mysqli_connect("xxxl","xxxx","xxxx","xxxl");



if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
  mysqli_query("SET CHARSET utf8", $con);
  mysqli_query("SET NAMES 'utf8' COLLATE 'utf8_bin'", $con);
  $tablica_wynikow = array();
   $pobrane_dane = mysqli_query($con, "SELECT * FROM wiadomosci");
    while($nt=mysqli_fetch_assoc($pobrane_dane)){ 
    $tablica_wynikow[] = $nt;

    }
header('Content-Type: application/json');
echo json_encode($tablica_wynikow);
}
mysqli_close($con);
}
if (isset($_POST["nowa_wiadomosc"])) //hre is post part
{
    $tresc_wiadomosci = $_POST["nowa_wiadomosc"];
    $con=mysqli_connect("xxx","xxx","xxx","xxxx");



   if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: ";
   }
   else
   {
     mysqli_query("SET CHARSET utf8", $con);
     mysqli_query("SET NAMES 'utf8' COLLATE 'utf8_bin'", $con);
     mysqli_query("INSERT INTO wiadomosci (tresc_wiadomosci) values  ($tresc_wiadomosci)");
   }

   mysqli_close($con);  
}
?>

这就是我尝试从c#app发送POST的方式:

System.Net.WebClient client = new System.Net.WebClient();
string result = client.UploadString("xxxxxxxx/wiadomosci.php?", "nowa_wiadomosc=TESTTTTT");
Console.WriteLine(result);

但结果我得到了一些随机网站的HTML代码,并没有添加新记录。 如果有人能指出我正确的方向。

编辑:它固定。我开始越来越多地对它进行debbuging,这在php脚本中是错误的查询构造,现在一切正常。

无论如何,谢谢你们。

1 个答案:

答案 0 :(得分:2)

您可以尝试以下发送POST请求。

using (var wb = new WebClient())
{
    var data = new NameValueCollection();
    data["nowa_wiadomosc"] = "TESTTTTT";


    var response = wb.UploadValues("xxxxxxxx/wiadomosci.php?", "POST", data);
}

结帐帮助 - LINK