C# HttpWebRequest错误403
我是C#新手,需要从C#检索url。大多数情况下,它工作正常,但在一个情况下,它抛出了一个错误。网址如下 错误为: HTTP url请求中出现异常:远程服务器返回错误:(403)禁止 我的代码是C# HttpWebRequest错误403,c#,.net,C#,.net,我是C#新手,需要从C#检索url。大多数情况下,它工作正常,但在一个情况下,它抛出了一个错误。网址如下 错误为: HTTP url请求中出现异常:远程服务器返回错误:(403)禁止 我的代码是 void MyFUnction(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = ".NET Framework Test Client
void MyFUnction(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = ".NET Framework Test Client";
request.ContentType = "application/x-www-form-urlencoded";
Logger.WriteMyLog("application/x-www-form-urlencoded");
// execute the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
if (httpData == null)
httpData = tempString;
else
httpData += tempString;
}
}
while (count > 0); // any more data to read?
}
删除ContentType行
request.ContentType....
您没有执行表单发布,只检索带有“GET”的页面
并将Accept属性设置为“text/html”
设置为格式化代码,在编辑器中选择它,然后按Control-K。这很好。在添加了三行initilization之后,我成功地做到了这一点:“webRequest.Method=“GET”;webRequest.UserAgent=“Foo”;webRequest.Accept=“text/html”虽然这篇文章很老了,但我今天(2016年10月15日)对它进行了更新投票,因为今天我在尝试学习网络垃圾时也遇到了类似的问题。我在stackoverflow上发布了这个问题,但有人指出已经有一个类似的问题,因此我删除并搜索了可用的答案。上面给出的答案对解决我自己的问题真的很有帮助。好的@Mikael Svenson
request.Method = "GET"; //this is the default behavior
request.Accept = "text/html";
request.Accept = "text/html";
void MyFunction(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = ".NET Framework Test Client";
request.Accept = "text/html";
Logger.WriteMyLog("application/x-www-form-urlencoded");
// execute the request
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(
resStream,
Encoding.GetEncoding(response.CharacterSet)
);
httpData = streamReader.ReadToEnd();
}
}