2013-02-22 54 views
1

HI我一直試圖從我的C#代碼發佈數據到PHP web服務(第三方)。 PHP的webservice表示它期望一個參數c(缺少參數c是我得到的錯誤)。 我正在使用JSON發送數據,但我不明白如何給參數。如果有人能說明這一點,那將是非常好的。以下是我的代碼:從C#發佈數據到PHP#

DropYa d = new DropYa(); 
List<DropYaUser> d1 = new List<DropYaUser>(); 
DropYaUser ds = new DropYaUser(); 
ds.action = "create"; 
ds.groupid = 10; 
ds.name = "Test"; 
ds.manager_key = "test"; 
d1.Add(ds); 

WebRequest request = WebRequest.Create(" http://dev.dropya.net/api/Group.php"); 
// Set the Method property of the request to POST. 
request.Method = "POST"; 
// Create POST data and convert it to a byte array. 
JavaScriptSerializer ser = new JavaScriptSerializer();//typeof(DropYaUser)); 

string postData = ser.Serialize(ds); 
byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
// Set the ContentType property of the WebRequest. 
request.ContentType = "application/json"; 

// Set the ContentLength property of the WebRequest. 
request.ContentLength = byteArray.Length; 
// Get the request stream. 

Stream dataStream = request.GetRequestStream(); 
// Write the data to the request stream. 
dataStream.Write(byteArray, 0, byteArray.Length); 
// Close the Stream object. 
dataStream.Close(); 
Console.Write("Wrote"); 
Console.Read(); 
// Get the response. 
WebResponse response = request.GetResponse(); 
// Display the status. 
Console.WriteLine(((HttpWebResponse)response).StatusDescription); 
// Get the stream containing content returned by the server. 
Console.Read(); 

dataStream = response.GetResponseStream(); 
Console.Read(); 
// Open the stream using a StreamReader for easy access. 
StreamReader reader = new StreamReader(dataStream); 
// Read the content. 
string responseFromServer = reader.ReadToEnd(); 
// Display the content. 
Console.WriteLine(responseFromServer); 
// Clean up the streams. 
reader.Close(); 
dataStream.Close(); 
Console.Read(); 
response.Close(); 

回答

1

任何發佈的請求將被讀作數據流。發佈表單的字段名稱和值將以類似「c = ABC & d = 123」的形式出現在數據流中,其中'c'和'd'是表單字段。當然,您可以發佈沒有任何表單字段名稱,但在這種情況下,它期望'c'。你想要做的是在你發佈的數據前加上「c =」。也許修改你的GetBytes行如下:

byte[] byteArray = Encoding.UTF8.GetBytes("c=" + postData); 
+0

謝謝你的回答 – Diva 2013-02-22 12:07:08

+0

沒問題。你有機會嘗試它嗎? – Matt 2013-02-22 17:10:06