2016-06-09 105 views
0

所以我试图设置远程PHP脚本的POST数据。该脚本使用POST数据作为文件名并用它检索JSON文件。但这可悲的是不起作用。它检索没有值的数据。下面是它如何工作的:C#WebClient上传字符串无法正常工作

C#:

using (WebClient client = new WebClient()) 
{ 
    byte[] saveData = client.UploadData(
     "http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "storeData.php", 
     "POST", 
     System.Text.Encoding.ASCII.GetBytes("filename="+ dt.bedrijfsNaam)); 
} 

PHP:

<?php 
$host='myip'; 
$user='username'; 
$pass='userpass'; 
$db='mydatabase'; 

$link= mysqli_connect($host, $user, $pass, $db) or die(msqli_error($link)); 

$filename = $_POST['filename'] . '.json'; 

$json = file_get_contents(__DIR__."/json/".$filename);// my thoughts are that something is wrong in this line? 
$obj = json_decode($json); 

$query_opslaan = "INSERT INTO skMain (BedrijfsName, ContPers, TelNum, email, Land, Plaats, PostCode) VALUES ('". $obj->bedrijfsNaam ."' , '". $obj->ContPers ."', '". $obj->TelNum ."', '". $obj->email ."', '". $obj->Land ."', '". $obj->Plaats ."', '". $obj->PostCode ."')"; 

mysqli_query($link, $query_opslaan) or die(mysqli_error($query_opslaan)); 
?> 

应该从JSON文件中获取正确的数据,而是它检索没有价值这一切,并查询商店空白数据进入数据库。我想我错误地使用了C#脚本,这就是为什么我也认为$ json变量无法正常工作。但我不完全知道我做错了什么。有人可以帮帮我吗?

+0

是什么'ConfigurationManager.AppSettings [ “scripturi”]的价值。的ToString()' –

+0

www.mydomain.eu/ –

+0

检查这个http://stackoverflow.com/a/25005434/5001784 –

回答

0

当你查找的PHP的文档$_POST,你会发现:

的使用应用程序/时通过HTTP POST方法传递的变量组成的关联数组的X WWW的形式,进行了urlencoded或multipart/form-data作为请求中的HTTP Content-Type。

这意味着您到服务器的POST的内容必须是其中的一种内容类型,它的正文需要与期望的格式相匹配。

在您的代码中,您使用UploadData方法。该方法对你没有任何魔法。它只是发布你给它的字节。您的要求将是这样的线:

POST /questions/ask HTTP/1.1 
Host: stackoverflow.com 
Content-Length: 13 
Expect: 100-continue 
Connection: Keep-Alive 

filename=test 

你看有没有Content-Type头。

然而,有称为UploadValues的其它方法,该方法需要一个NameValueCollection并转换它的内容到所需要的X WWW的form-urlencoded格式为您:

using(var wc= new WebClient()) 
{ 
     var nv = new System.Collections.Specialized.NameValueCollection(); 
     nv.Add("filename", "test"); 
     nv.Add("user", "bar"); 
     wc.UploadValues("http://stackoverflow.com/questions/ask", nv); 
} 

当执行下面被发送到服务器:

POST /questions/ask HTTP/1.1 
Content-Type: application/x-www-form-urlencoded 
Host: stackoverflow.com 
Content-Length: 22 
Expect: 100-continue 

filename=test&user=bar 

这最后的主体内容将导致一个人口$_POST阵列机智h 文件名用户

当调试这些类型的请求时,请确保您运行Fiddler,以便您可以检查HTTP通信。