我正在尝试向 C# 中的网站发送 POST 请求,然后解析响应中的 html 以从中获取某些项目名称。但是,在我运行程序的大约 50% 的时间里,我会收到 408 错误。这是我的代码(大部分来自这里:https ://msdn.microsoft.com/en-us/library/debx8sh9.aspx ):
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Net;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Linq;
using Fizzler.Systems.HtmlAgilityPack;
class FinderClass
{
//some irrelevant code here
public int getItemIndex(string itemName)
{
itemName = itemName.Replace(" ", "+"); //formatting for request
itemName = itemName.Replace("|", "%7C");
//taken from https://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx :
WebRequest request = WebRequest.Create("http://csgolounge.com/ajax/tradeCsRightTmp.php"); //address to send request
request.Method = "POST";
string postData = "type=Type+-+All&quality=0&exterior=0&fraze=" + itemName + "&search=1&page=1"; //request parameters
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Debug.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Debug.WriteLine(responseFromServer); //print response to debug console (temporary)
reader.Close();
dataStream.Close();
response.Close();
return -1; //placeholder for when item index is parsed from html and returned
}
}
抛出的异常:
System.dll 中出现“System.Net.WebException”类型的未处理异常
附加信息:远程服务器返回错误:(408) 请求超时。
通常我会认为有一个简单的解决方案,但由于它只发生在我运行程序的一半时间,它可能会更复杂。