我需要从网站上获取一些信息。该网站无意从浏览器访问。所以我们假设该网站包含一个字节数组:我想从控制台应用程序中获取该字节数组。
// 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>
如果'data'是一个字符串,我可以通过解析以下代码中定义的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个字符。也许我应该使用不同类型的编码。但我必须确保我的网站支持我使用的任何类型的编码......
答案 0 :(得分:1)
使用与
类似的东西byte[] myBinaryResponse = new byte[response.ContentLength];
response.GetResponseStream().Read (myBinaryResponse, 0, myBinaryResponse.Length);
答案 1 :(得分:1)
继上述评论之后,您可能希望查看有关处理程序的本教程(正如克里斯热烈建议的那样)http://www.dotnetperls.com/ashx
这也可能有助于提供最终目标的更多细节。你总是试图推出一个字节数组吗?如果是这样,也许Web服务可能有所帮助。 A web service tutorial
您将如何使用此数据?在不同的网页或Windows应用程序中?