System.Net.WebException: 远程服务器返回错误: (400) 错误的请求。

System.Net.WebException: 远程服务器返回错误: (400) 错误的请求。
在 System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
在 System.Net.WebClient.UploadString(Uri address, String method, String data)
在 System.Net.WebClient.UploadString(String address, String data)
在 UserMesLib.MaiWe.UpLoadData(String startTime, String endTime, String testTime, String windowSeq, String testResult, String log, String XmlFileName, String TxtFileName, String mac)

try
{
    var rsp = (System.Net.HttpWebResponse)req.GetResponse();//正常情况获取web服务器返回数据
}
catch (System.Net.WebException ex)
{
    Debug.Write(ex.Message);//远程服务器返回错误: (400) 错误的请求。
    var strResponse = GetResponseAsString((System.Net.HttpWebResponse)ex.Response,encoding);//这样获取web服务器返回数据
}
string GetResponseAsString(HttpWebResponse res, Encoding encoding)
{
    try
    {
        StreamReader sr = new StreamReader(res.GetResponseStream(), encoding);
        return  sr.ReadToEnd();               
    }
    catch (Exception ex)
    {        
        return "";
    }
}

参考

WebException远程服务器返回错误: (400) 错误的请求。

HttpWebRequest 在出错时获取response内容

获得HttpWebResponse请求的详细错误内容

原文地址:https://www.cnblogs.com/code1992/p/13916181.html