我需要从网站获取一些信息。该网站不打算从浏览器访问。所以假设该网站包含一个字节数组:我想从控制台应用程序获取该字节数组。通过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