2010-02-11 69 views
6

我有一個客戶端和一個服務器。HttpWebRequest/HttpResponse:如何在響應中發送數據?

在客戶端,我有:

HttpWebRequest request = 
    (HttpWebRequest)WebRequest.Create("http://localhost/fa/Default.aspx"); 
request.Method = "POST";     

byte[] data = Encoding.ASCII.GetBytes(GetSAMLRequestB64()); 

request.ContentType = "text/xml"; 
request.ContentLength = data.Length; 
Stream stream = request.GetRequestStream(); 
stream.Write(data, 0, data.Length); 

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
Stream responseStream = response.GetResponseStream(); 

在服務器端,我有:

public void ProcessRequest(HttpContext httpContext) 
{ 
    HttpResponse response = httpContext.Response;    
    response.Clear(); 
    response.BufferOutput = true; 
    response.StatusCode = 200; // HttpStatusCode.OK; 
    response.Write("Hello"); 
    response.ContentType = "text/xml"; 
    response.End(); 
} 

客戶端接收與正確StatusCode的響應。雖然,如果我在客戶端上執行(int)response.ContentLength;,我得到0.在收到響應(客戶端)後,我無法讀取字符串「Hello」。

+1

我知道這是一個古老的線程,但可能有助於某人。 嘗試http://stackoverflow.com/questions/4088625/net-simplest-way-to-send-post-with-data-and-read-response/19448979#19448979 – Murali 2013-10-18 12:16:38

回答

3

也許在實際寫入或刷新流之前設置內容類型會有所幫助。

+0

我做到了,但是有一個副本/過去的問題...所以,仍然不適用於內容類型。 – user252816 2010-02-11 20:12:12

1

您沒有在服務器上設置ContentLength。也許這會有所幫助?

+0

如何在服務器上設置contentLength? – user252816 2010-02-11 20:12:32

+0

'response.ContentLength = n;'不起作用?如果沒有,那麼我錯誤地認爲ContentLength是你的問題。 – 2010-02-11 21:11:01

相關問題