净HttpWebRequest.GetResponse()时,HTTP状态code 400(错误请求)返回引发异常 [英] .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

查看:5397
本文介绍了净HttpWebRequest.GetResponse()时,HTTP状态code 400(错误请求)返回引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在的情况下,当我得到一个HTTP 400 code从服务器,它是服务器,告诉我什么是错的我的要求的完全合法的方式(使用HTTP响应内容的消息)

I am in a situation where when I get an HTTP 400 code from the server, it is a completely legal way of the server telling me what was wrong with my request (using a message in the HTTP response content)

但是,.NET的HttpWebRequest引发异常时的状态code为400。

However, the .NET HttpWebRequest raises an exception when the status code is 400.

我要如何处理呢?对我来说,400是完全合法的,并且相当有帮助的。 HTTP内容有一些重要的信息,但除了抛出我了我的道路。

How do I handle this? For me a 400 is completely legal, and rather helpful. The HTTP content has some important information but the exception throws me off my path.

推荐答案

这将是很好,如果有关闭的某种方式扔在非成功code,但如果你赶上WebException你至少可以使用回应:

It would be nice if there were some way of turning off "throw on non-success code" but if you catch WebException you can at least use the response:

using System;
using System.IO;
using System.Web;
using System.Net;

public class Test
{
    static void Main()
    {
        WebRequest request = WebRequest.Create("http://csharpindepth.com/asd");
        try
        {
            using (WebResponse response = request.GetResponse())
            {
                Console.WriteLine("Won't get here");
            }
        }
        catch (WebException e)
        {
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse) response;
                Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                using (Stream data = response.GetResponseStream())
                using (var reader = new StreamReader(data))
                {
                    string text = reader.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }
    }
}

您可能想封装的给我一个答复,即使它不是一个成功的code位在一个单独的方法。 (我建议你还是扔掉,如果没有响应,例如,如果您无法连接。)

You might like to encapsulate the "get me a response even if it's not a success code" bit in a separate method. (I'd suggest you still throw if there isn't a response, e.g. if you couldn't connect.)

如果错误响应可能很大(这是不寻常的),你可能需要调整<一href="https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.defaultmaximumerrorresponselength"><$c$c>HttpWebRequest.DefaultMaximumErrorResponseLength以确保您得到整个错误。

If the error response may be large (which is unusual) you may want to tweak HttpWebRequest.DefaultMaximumErrorResponseLength to make sure you get the whole error.

这篇关于净HttpWebRequest.GetResponse()时,HTTP状态code 400(错误请求)返回引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆