douzou8074
douzou8074
2017-12-07 10:56

使用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 doulian7305 4年前

    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".

    点赞 评论 复制链接分享

为你推荐