如何解决c# 在面板中显示 Web 请求响应
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");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。