HttpWebRequest.GetRequestStream()引发400异常后,怎么样获取确切的错误信息

.Net技术 码拜 8年前 (2016-02-27) 2652次浏览
HttpWebRequest 发post请求,失败后,引发了如下异常:

ResponseStatusCode “request.ResponseStatusCode”引发了“System.NullReferenceException”类型的异常	System.Net.HttpStatusCode {System.NullReferenceException}

远程服务器返回400;用fiddler抓请求显示返回的信息如下:

HTTP/1.1 400 Bad Request
Content-Type: application/json
Date: Thu, 11 Sep 2014 10:09:42 GMT
Server: TornadoServer/2.1git-cl
Set-Cookie: bsid=f0f7dc2616b44a4ea4265b8b8eef9803; Path=/
X-Merch-Hostname: wish-merchant-fe-313e336f
X-Merch-Version: 20140911041521
Content-Length: 96
Connection: keep-alive
{"message":"\u5fc5\u586b\u5217 Main Image URL \u672a\u586b\u5199\u3002","code":1000,"data":2202}

“message”:”\u5fc5\u586b\u5217 Main Image URL \u672a\u586b\u5199\u3002″,”code”:1000,”data”:2202 是一串确切的错误提示,程序里应该怎么获取这个呢?

解决方案

40

你可以试试
try {

HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create(“invalid site”);
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine(“This program is expected to throw WebException on successful run.”+
“\n\nException Message :” + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
HttpWebResponse x = e.Response as HttpWebResponse;
x里面可以得到
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}

40

参考: .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

using System;
using System.IO;
using System.Net;
public class Test
{
	static void Main()
	{
		HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://csharpindepth.com/asd");
		try
		{
			using (Stream data = request.GetResponse().GetResponseStream())
			{
				using (StreamReader reader = new StreamReader(data))
				{
					string text = reader.ReadToEnd();
					Console.WriteLine(text);
				}
			}
		}
		catch (WebException ex)
		{
			HttpWebResponse response = (HttpWebResponse) ex.response;
			Console.WriteLine("Error code: {0}", response.StatusCode);
			if (response.StatusCode == HttpStatusCode.BadRequest)
			{
				using (Stream data = response.GetResponseStream())
				{
					using (StreamReader reader = new StreamReader(data))
					{
						string text = reader.ReadToEnd();
						Console.WriteLine(text);
					}
				}
			}
		}
	}
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明HttpWebRequest.GetRequestStream()引发400异常后,怎么样获取确切的错误信息
喜欢 (0)
[1034331897@qq.com]
分享 (0)