c# 在面板中显示 Web 请求响应
c# Display web request response in a panel
1
您好,我想在此面板中显示网站的响应,我该怎么做。我有必要的 System.Net 等。代码如下:
private void panel7_Paint(object sender, PaintEventArgs e)
{
WebRequest request = WebRequest.Create("http://www.contoso.com/default.html");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
}
我是否需要将 webresponse 设置为字符串而不是将其作为字符串 tx 传递?
[所述面板的代码]
the code of the panel in cs
[3]: https://i.stack.imgur.com/DBY9w.png //我要显示数据的面板。
我相信你需要面板中的标签,然后将其 label.Text
属性 更改为响应正文。
要从 HttpWebResponse
读取响应正文,请参阅 this answer。
如果您使用 .NET Core 3 或更高版本,我还建议您切换到现代 HttpClient
API:
using var httpClient = new HttpClient();
示例:
using var httpRequest = new HttpRequestMessage(HttpMethod.Get, "http://www.contoso.com/default.html");
using var httpResponse = await httpClient.SendAsync(httpRequest);
label.Text = await httpResponse.Content.ReadAsStringAsync();
或者更简单,如果您根本不需要编辑请求消息:
label.Text = await httpClient.GetStringAsync("http://www.contoso.com/default.html");
1 您好,我想在此面板中显示网站的响应,我该怎么做。我有必要的 System.Net 等。代码如下:
private void panel7_Paint(object sender, PaintEventArgs e)
{
WebRequest request = WebRequest.Create("http://www.contoso.com/default.html");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
}
我是否需要将 webresponse 设置为字符串而不是将其作为字符串 tx 传递?
[所述面板的代码] the code of the panel in cs
[3]: https://i.stack.imgur.com/DBY9w.png //我要显示数据的面板。
我相信你需要面板中的标签,然后将其 label.Text
属性 更改为响应正文。
要从 HttpWebResponse
读取响应正文,请参阅 this answer。
如果您使用 .NET Core 3 或更高版本,我还建议您切换到现代 HttpClient
API:
using var httpClient = new HttpClient();
示例:
using var httpRequest = new HttpRequestMessage(HttpMethod.Get, "http://www.contoso.com/default.html");
using var httpResponse = await httpClient.SendAsync(httpRequest);
label.Text = await httpResponse.Content.ReadAsStringAsync();
或者更简单,如果您根本不需要编辑请求消息:
label.Text = await httpClient.GetStringAsync("http://www.contoso.com/default.html");