我需要從網站獲取一些信息。該網站不打算從瀏覽器訪問。所以假設該網站包含一個字節數組:我想從控制檯應用程序獲取該字節數組。通過webrequest從asp.net網站接收byte []
// c# code for asp website
protected byte[] data;
protected void Page_Load(object sender, EventArgs e)
{
data = new byte[] { 1, 100, 200, 255 }; // the byte array that I want to send
}
// the asp content
<body>
<form id="form1" runat="server">
<div>
<%=data%>
</div>
</form>
</body>
如果「數據」將是一個字符串,我就可以通過分析在下面的代碼中定義的變量responseFromServer檢索。
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://localhost:4444/WebSite2/HelloFromC.aspx");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// 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();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// 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();
response.Close();
,我曾嘗試事情:
我試圖字節數組{1,100,200,255}轉換爲ASCII。然後用編碼類將其轉換回字節數組。 ASCII的問題是它不包含256個字符。也許我應該使用不同類型的編碼。但是,我必須確保,無論編碼我用的就是通過我的網站的支持......
你看過用Web服務做這個嗎? – Matt
目前尚不清楚您的問題是發送發佈數據還是收到響應數據。你有沒有看過WebClient的方式?這對於像這樣的事情要簡單得多... –
請勿爲您的網站使用常規的aspx頁面。使用ashx文件(通用處理程序)。您可以完全控制發佈的標記。 – NotMe