我在之前写过一个有关于C#post请求的,详情移步这里
由于非200直接进入catch代码块,导致不知道网页输出的是什么错误,这个文章就对非200部分做了处理
public static string RequestContent(string URL, string method, string postData, Dictionary<string, string> heads)
{
byte[] postBytes = Encoding.GetEncoding("utf-8").GetBytes(postData);
string result = string.Empty;
try
{
HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(URL);
//HttpWReq.Headers.Add("Accept-Encoding", "gzip,deflate");//sdch
HttpWReq.Method = method;
if (method.ToUpper() == "POST")
{
HttpWReq.ContentType = "application/x-www-form-urlencoded";
HttpWReq.ContentLength = postBytes.Length;
//HttpWReq.Headers.Add("Authorization","Unauthorized");
using (Stream reqStream = HttpWReq.GetRequestStream())
{
reqStream.Write(postBytes, 0, postBytes.Length);
}
}
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
StreamReader reader = new StreamReader(HttpWResp.GetResponseStream(), Encoding.Default);
result = reader.ReadToEnd();
HttpWResp.Close();
}
catch (WebException e)
{
//string msg = e.Message;
HttpWebResponse response = (HttpWebResponse)e.Response;
using (Stream data = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(data, Encoding.Default))
{
result = reader.ReadToEnd();
}
}
}
return result;
}
微信扫码查看本文
发表评论