C#如何通过HTTP将数据发布到PHP并运行它

时间:2016-06-07 14:29:33

标签: c# php json

所以我有一个应用程序,它使用来自用户的一些数据创建一个JSON文件。这些数据应该通过我服务器上的PHP脚本解码并存储到数据库中。我想将$ _POST变量 filename 发布到php脚本,以使用它来检索JSON文件。这是我目前的PHP脚本:

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

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

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

$json = file_get_contents($filename);
$obj = json_decode($json,true);

foreach ($obj as $data) 
{
$query_opslaan = "INSERT INTO skMain (BedrijfsName, ContPers, TelNum, email, Land, Plaats, PostCode) VALUES ('". $data['bedrijfsNaam'] ."' , '". $data['ContPers'] ."', '". $data['TelNum'] ."', '". $data['email'] ."', '". $data['Land'] ."', '". $data['Plaats'] ."', '". $data['PostCode'] ."')";
}
?>

这是我的JSON文件

{
"bedrijfsNaam":"JohnDoeMedia",
"ContPers":"John Doe",
"TelNum":"1234567890",
"email":"test@test.nl",
"Land":"Nederland",
"Plaats":"somewhere",
"PostCode":"1234 AB"
}

我目前只有C#中的上传脚本,但我不知道如何使用它来运行这个PHP脚本并将数据存储到PHP变量 $ _ POST ['filename'] 这里是商店脚本:

        WebRequest hwr = WebRequest.Create(serverPath);
        hwr.Method = WebRequestMethods.Ftp.UploadFile;
        hwr.Credentials = new NetworkCredential(ftpUser, ftpPass);

        if (reqCat == "bvg")
        {
            json = "{\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
                            "\"ContPers\":\"" + ContPers + "\"," +
                            "\"TelNum\":\"" + TelNum + "\"," +
                            "\"email\":\"" + email + "\"," +
                            "\"Land\":\"" + Land + "\"," +
                            "\"Plaats\":\"" + Plaats + "\"," +
                            "\"PostCode\":\"" + PostCode + "\"}";
            using (var sw = new StreamWriter(hwr.GetRequestStream()))
            {
                sw.Write(json);
                sw.Flush();
                sw.Close();
            }
        }

有人可以教我使用这种方法吗?

1 个答案:

答案 0 :(得分:1)

我要去捅这个,因为我觉得你可能很困惑。您提到您正在尝试POST数据,但您的代码显示您正在尝试直接FTP到服务器。

我已将用于FTP的代码包含在服务器中。如果你真的想通过网络服务电话发帖,那就不会这样做。

        FtpWebRequest lRequest = (FtpWebRequest)WebRequest.Create(serverPath);          
        lRequest.Method = WebRequestMethods.Ftp.UploadFile;
        lRequest.Credentials = new NetworkCredential(ftpUser, ftpPass);
        StreamReader lReader = new StreamReader(json);

        //convert steam to utf8
        byte[] lContents = Encoding.UTF8.GetBytes(lReader.ReadToEnd());
        lReader.Close();

        //Get length of data to post
        lRequest.ContentLength = lContents.Length;

        //Get your request stream
        Stream lRequestStream = lRequest.GetRequestStream();

        //Write to the stream
        lRequestStream.Write(lContents, 0, lContents.Length);

        //Close the stream
        lRequestStream.Close();

        //Get the response from the server
        FtpWebResponse lResponse = (FtpWebResponse)lRequest.GetResponse();

        //What is the actual status.
        MessageBox.Show(String.Format("Upload File Complete, status {0}", lResponse.StatusDescription));

请注意,你必须使用和你一样的东西,但我已经使用该代码ftp到服务器。我稍微修改了它以尝试使用你的变量名。

由于请求是使用HTTP只发送文件名,我已将其添加到我的答案中。在下面的代码中,最重要的部分是uri。我假设您可以创建您的URI作为运行PHP的Web服务。它看起来像......在哪里SERVERPATH是你的服务器与script.php并假设你的PHP脚本正在寻找的参数称为FileName。该代码还包括处理来自服务器的响应,但您可能不需要这样做,具体取决于您希望服务器执行的操作。

另请注意,除非您希望从服务器返回,否则accept和content类型可能不相关。您最关心的两行是WebRequest.Create(xUri)和实际执行Web请求的lRequest.GetResponse()。

的http:// <强> SERVERPATH / <强> PHP_SCRIPT 文件名= <强> FILENAME

private void CallWebApi(String xUri)
    {
        String lResults;
        using(WebClient lClient = new WebClient()) {
            try {
                HttpWebRequest lRequest = (HttpWebRequest)WebRequest.Create(xUri);
                lRequest.Accept = "application/json";
                lRequest.ContentType = "application/json";
                HttpWebResponse lResponse = (HttpWebResponse)lRequest.GetResponse();
                using(StreamReader lJsonReader = new StreamReader(lResponse.GetResponseStream())) {
                    lResults = lJsonReader.ReadToEnd();
                }

                lRequest = (HttpWebRequest)WebRequest.Create(xUri);
                lRequest.Accept = "application/xml";
                lRequest.ContentType = "application/xml";
                lResponse = (HttpWebResponse)lRequest.GetResponse();
                using(StreamReader lXMLReader = new StreamReader(lResponse.GetResponseStream())) {
                    lResults = lXMLReader.ReadToEnd();
                }

            }
            catch(Exception lException) {
                MessageBox.Show(lException.Message);
            }
        }
    }