[英]How to send the result of a PHP function to a c# Client?
我將從函數php到C#WinApp Client中檢索Return值。
我在php頁面中有一些功能。 這些函數使用Get Method並詳細說明從C#Winapp Client接收的一些數據。
因此,精心制作數據后的php頁面會返回一個值。 現在,我將從C#客戶端獲取此值。
我可以“即時”執行此操作,而無需在PC客戶端上保存任何文件。
我怎樣才能做到這一點?
編輯:如果有人可以用Json或XML做示例,我將不勝感激。
您需要在服務器上創建一個PHP腳本來檢索所需的數據,然后以SOAP,XML或JSON的形式返回結果,然后可以使用WebRequest
( MSDN鏈接 )從C#應用程序中請求該頁面。
一個帶有JSON輸出的簡單示例:
PHP代碼:
<?php
#header('content-type:application/json');
if(array_key_exists("foo", $_POST) && !empty($_POST["foo"])) {
$data = array('foo' => 'baa', 'x' => 'y', 'sucess' => 'true', 'error' => 'null');
}
else {
$data = array('error' => 'foo is empty', 'sucess' => 'false');
}
die(json_encode($data));
?>
C#.NET代碼:
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
namespace App
{
class Program
{
static void Main(string[] args)
{
string response = DoRequest();
JavaScriptSerializer ser = new JavaScriptSerializer();
View json = ser.Deserialize<View>(response);
if (json.sucess)
{
// do something..
}
else
{
Console.WriteLine("Erro:{0}", json.error);
}
}
static string DoRequest()
{
string domain = "..."; // your remote server
string post = "foo=baa";
byte[] data = Encoding.ASCII.GetBytes(post);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(domain);
request.Method = "POST";
request.Referer = "desktop C# Application";
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
char[] buffer = new char[256];
int count;
StringBuilder buf = new StringBuilder();
while ((count = sr.Read(buffer, 0, 256)) > 0)
{
buf.Append(buffer, 0, count);
}
response.Close();
stream.Close();
sr.Close();
return buf.ToString();
}
}
public class View
{
public string foo { get; set; }
public string x { get; set; }
public bool sucess { get; set; }
public string error { get; set; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.