douzou8074
2017-12-07 10:56
浏览 70

使用C#和PHP从远程服务器获取回复

I'm trying to get data from a remote server using C#. I tried using a simple script to see if "it works", but I'm not getting a response. The same script works on a local server, so I'd like to know how I can do it.

This is my C# code:

IEnumerator Sayhi()
{
    WWWForm sendInfo = new WWWForm();
    sendInfo.AddField("function", function);

    WWW www = new WWW(bl_LoginDataBase.Instance.GetUrl(bl_LoginDataBase.URLType.CallFunction), sendInfo);
    yield return www;
    Debug.Log(www.text);
}

And the PHP code:

<?php
echo "Hi";

I expected the Debug.Log(www.text); to print Hi, which it does if I use a local machine (http://192.168.0.whatever), but the remote server (http://whatever.example.com) doesn't return anything. I tried making the php fail so it returns an error, make a database and return some values from there, but nothing. I'd like to point out it does work on a local server, and works as intended.

What am I doing wrong?

Edit: By the way, if I access http://www.whatever.example.com/Function.php via browser, it shows the echo result.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulian7305 2017-12-07 11:12
    已采纳

    C# has built in classes and methods to help you perform such tasks.You can use the WebClient class to connect to web servers (using GET or POST) and even send form values to it easily. See below:

    string url ="http://www.whatever.example.com/Function.php";
    
    var reqparam = new System.Collections.Specialized.NameValueCollection();
    
    reqparam.Add("name", "John Doe");
    
    try
    {
        using (System.Net.WebClient client = new System.Net.WebClient())
        {
    
         byte[] responsebytes = client.UploadValues(url, "POST", parameters);
    
         string output = System.Text.Encoding.UTF8.GetString(responsebytes);
    
         }
    }
    catch (Exception x)
    {
       //an error occured
    }
    

    The variable output will contain the response you want "Hi".

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题