понедельник, 3 марта 2014 г.

417 Expectation Failed

На днях потребовалось научить одну .net-программулину работать через прокси. Быстренько были внесены изменения в интерфейс настроек, заполнено свойство Proxy объекта класса HttpWebRequest. Но тут что-то пошло не так. Страничка в Firefox открывалась, а вот при попытке выполнить запрос через софтину мы получали ответ от сервера 417 Expectation Failed. После прочтения материала и просмотра заголовков, отправляемых приложением, стало понятно, что объект HttpRequest при отправке POST-запроса автоматически добавляет заголовок Expect. А прокси-сервер Squid3 по умолчанию отвергает такие запросы с кодом ошибки 417:
#  TAG: ignore_expect_100       on|off
#       This option makes Squid ignore any Expect: 100-continue header present
#       in the request. RFC 2616 requires that Squid being unable to satisfy
#       the response expectation MUST return a 417 error.
#
#       Note: Enabling this is a HTTP protocol violation, but some clients may
#       not handle it well..
#Default:
#ignore_expect_100 off
Хотя правильнее отключить применение этого заголовка при работе через прокси:
         string postData = String.Format("lg={0}&pw={1}", login, pass);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LOGIN_URL);
            request.Proxy = proxy;
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(cookie);
            request.Method = WebRequestMethods.Http.Post;
            request.AllowWriteStreamBuffering = true;
            request.ProtocolVersion = HttpVersion.Version11;
            request.AllowAutoRedirect = true;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = REQTIMEOUT;
            request.ServicePoint.Expect100Continue = proxy == null;