c# - C# HttpClient() getStringASync() 404 (Not Found)
问题描述
So i'm trying to make a basic Console Application that simply gets the visible text on the webpage. But for example, if the page is not found, i'm getting an error. I'm not sure how i'd be able to fix this error, like, if it errors i want it to just ignore it. I tried adding a if statement but it does the exact same.
HttpClient client = new HttpClient();
string content = await client.GetStringAsync("https://www.yourwebsite.com/);
解决方案
所以你可以捕获 HttpRequestException,但我的建议是不要使用 GetStringAsync 更好的方法是使用 GetAsync 方法
HttpClient client = new HttpClient();
var response = await client.GetAsync("https://www.yourwebsite.com");
if (response.IsSuccessStatusCode) {
var getResponsestring = await response.Content.ReadAsStringAsync();
}
else {
... your logic here
}
推荐阅读
- vue.js - Nuxt 中间件创建无限重定向
- android - 如何从 contentprovider 获取联系人,其中特定号码的 contact_id 最大值
- node.js - NPM 在安装新依赖项时删除所需的依赖项
- visual-studio-code - VScode 停止使用 ElixirLS 插件,系统冻结。LinuxMint 机器
- php - 在 php 中将 windows-1256 转换为 utf-8 或将 utf-8 转换为 windows-1256
- python-3.x - 无法使用 python 显示有符号的无符号字节
- jmeter - JMeter 分布式负载测试 - 本地系统中的主机和 AWS EC2 Windows 实例中的从机 - 无法连接
- security - 如何防止在 Active Directory 上与同一用户同时登录?
- javascript - 在重复嵌套的数组中查找对象和父对象
- java - NoUniqueBeanDefinitionException 当父类和子类是组件时