先描述一下问题产生,对接某公司程序时,由于返回请求错误,对方服务器返回400,415,等错误,然而这种异常内包含某些对方返回的信息,普通的如果post方法内未进行Response的异常处理,那么恭喜你,你悲剧了,获取到的信息就是这些“Exception:远程服务器返回错误: (500) 内部服务器错误”。然而这并不是我们想要的,那么就需要对这种情况进行处理了。(在此记录一下,方便日后查看)
下面先看一个post:
public string PostHtml(string url, string args)
{
return PostHtml(url, args, _webEncoding);
}
public string PostHtml(string url, string args, WebProxy proxy)
{
return PostHtml(url, args, _webEncoding, proxy);
}
public string PostHtml(string url, string args, Encoding enc, WebProxy proxy = null)
{
string result = null;
try
{
//enc = Encoding.UTF8;
var bytes = Encoding.UTF8.GetBytes(args);
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
var request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = _webCookieContainer;
request.Timeout = _timeout;
request.ReadWriteTimeout = _timeout;
request.UserAgent = _userAgent;
request.Referer = _referer;
request.ContentType = _contentType; //;//_contentType
request.Headers.Add("Cache-control: no-cache");
request.Headers.Add("Accept-Language: zh-cn");
request.Accept = "application/json";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.ProtocolVersion = HttpVersion.Version11;
if (proxy != null) request.Proxy = proxy;
using (var stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
request.ServicePoint.Address.ToString();
var response = (HttpWebResponse)request.GetResponse();
if (response.Cookies != null) _webCookieContainer.Add(response.Cookies);
var recvStream =response.GetResponseStream();
//response.CharacterSet = Encoding.GetEncoding("UTF-8");
if (recvStream != null)
{
if (response.ContentEncoding.ToLower().Contains("gzip"))
{
using (GZipStream stream = new GZipStream(recvStream, CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{
result = reader.ReadToEnd();
}
}
}
else if (response.ContentEncoding.ToLower().Contains("deflate"))
{
using (DeflateStream stream = new DeflateStream(recvStream, CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{
result = reader.ReadToEnd();
}
}
}
else
{
using (StreamReader reader = new StreamReader(recvStream, Encoding.GetEncoding("UTF-8")))
{
result = reader.ReadToEnd();
}
}
}
_lastUrl = response.ResponseUri.ToString();
response.Close();
request.Abort();
}
catch (Exception ex)
{
result = $"Exception:{ex.Message}";
}
return result;
}
异常直接return result,然而result中没有任何有用信息。
那就抛出异常处理一下看下一个post:
public string PianYunHttpPost(string Url, Dictionary<string, string> parms)
{
StringBuilder sb = new StringBuilder();
foreach (var item in parms)
{
if (sb.Length != 0)
sb.Append("&");
sb.Append(HttpUtility.UrlEncode(item.Key) + '=' + HttpUtility.UrlEncode(item.Value));
}
byte[] dataArray = Encoding.UTF8.GetBytes(sb.ToString());
// Console.Write(Encoding.UTF8.GetString(dataArray));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataArray.Length;
//request.CookieContainer = cookie;
try
{
Stream dataStream = request.GetRequestStream();
dataStream.Write(dataArray, 0, dataArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
String res = reader.ReadToEnd();
reader.Close();
//Console.Write("\nResponse Content:\n" + res + "\n");
return res;
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
//Console.WriteLine(e);
if (response == null)
{
return e.ToString();
}
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
// Console.WriteLine(text);
return text;
}
}
}
}
多出的地方就是catch webException
然而就是这个东西吧自身需要的东西给反回来了,问题就是这样。
下面这个是post解决乱码的问题,具体的编码方式自己搞下吧:
public string HttpPostData(String url, String data)
{
string strReturn = string.Empty;
byte[] byteData = Encoding.UTF8.GetBytes(data); //在转换字节时指定编码格式
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = byteData.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(byteData, 0, byteData.Length);//发送数据
}
//get reponse data and parse
using (WebResponse response = req.GetResponse())
{
//解决乱码:utf-8 + streamreader.readtoend
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
strReturn = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
}
catch (Exception ex)
{
throw ex;
}
return strReturn;
}