2009-08-10 40 views
0

我在我的C#應用​​程序發佈數據的網頁在C#中失敗

string verification_url = @"http://site.com/posttest.php?"; 
string verification_data = "test=524001A"; 
string result = string.Empty; 
result = Post(verification_url, verification_data); 

public string Post(string url, string data) 
{ 
    string result = ""; 
    try 
    { 
     byte[] buffer = Encoding.GetEncoding(1252).GetBytes(data); 
     HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(@url); 
     WebReq.Method = "POST"; 

     WebReq.ContentType = "application/x-www-form-urlencoded";    
     WebReq.ContentLength = buffer.Length; 
     Stream PostData = WebReq.GetRequestStream(); 

     PostData.Write(buffer, 0, buffer.Length); 
     PostData.Close(); 

     HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse(); 
     Stream Answer = WebResp.GetResponseStream(); 
     StreamReader _Answer = new StreamReader(Answer); 
     result = _Answer.ReadToEnd(); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
    if (result.Length < 0) 
    result = ""; 

    return result; 

} 

服務器端PHP代碼

<?php 
$test=$_REQUEST['test']; 
echo $test; 
?> 

後方法始終返回空值

請幫助使用下面的代碼我

+0

你的代碼工作正常。也許存在網絡配置問題,即防火牆,代理等。 – 2009-08-10 12:15:51

回答

0

我已經改變了以下行

string verification_url = @"http://site.com/posttest.php?"; 

string verification_url = @"http://www.site.com/posttest.php?"; 

現在工作得很好書面

1

嘗試

<?php 
print_r($_REQUEST); 
?> 

顯示原始REQUEST變量。即時通訊不知道你在哪裏設置你的C#代碼測試。

+0

print_r輸出 數組 ( ) – 2009-08-10 12:30:47

+0

檢查訪問日誌,我的猜測是請求不在服務器上。也許都鐸奧拉瑞的「.net許可」是你問題的關鍵。 – Rufinus 2009-08-10 12:47:10

0

您需要將驗證數據作爲參數添加到請求url中。

string verification_data = "test=524001A"; 
string verification_url = @"http://site.com/posttest.php?" + verification_data; 

這樣,你實際請求的URL將是:

http://site.com/posttest.php?test=524001A 
+0

但這只是一個get請求,因爲他設置了contenttype/length頭。 – Rufinus 2009-08-10 12:12:17

+0

不,它不會。他正在設置WebReq.Method =「POST」,編碼也是「application/x-www-form-urlencoded」。相信我,它會在查詢字符串中發佈數據,我之前做過。 – 2009-08-10 12:23:45

+0

這是我的財富,不需要c#。如果你說它會奏效,我相信你。我看起來很奇怪。 – Rufinus 2009-08-10 12:25:50

0

你能儘量不關閉RequestStream?嘗試刪除以下行:

PostData.Close(); 

PS:你有必要的.NET權限做到這一點?

+0

我已經刪除了上述的這一行仍然是空的結果 – 2009-08-10 12:33:22