当我尝试POST到一个URL时,会导致以下异常:

远程服务器返回错误: (417)期望失败。

下面是一个示例代码:

var client = new WebClient();

var postData = new NameValueCollection();
postData.Add("postParamName", "postParamValue");

byte[] responseBytes = client.UploadValues("http://...", postData);
string response = Encoding.UTF8.GetString(responseBytes); // (417) Expectation Failed.

使用HttpWebRequest/HttpWebResponse对或HttpClient没有区别。

是什么导致了这个异常?


当前回答

如果你正在使用“HttpClient”,并且你不想使用全局配置来影响你可以使用的所有程序:

 HttpClientHandler httpClientHandler = new HttpClientHandler();
 httpClient.DefaultRequestHeaders.ExpectContinue = false;

如果你正在使用“WebClient”,我认为你可以尝试删除这个头通过调用:

 var client = new WebClient();
 client.Headers.Remove(HttpRequestHeader.Expect);

其他回答

网络。config方法适用于InfoPath表单服务调用IntApp启用web服务的规则。

  <system.net>
    <defaultProxy />
    <settings> <!-- 20130323 bchauvin -->
        <servicePointManager expect100Continue="false" />
    </settings>
  </system.net>

另一种方式——

将这些行添加到应用程序配置文件配置部分:

<system.net>
    <settings>
        <servicePointManager expect100Continue="false" />
    </settings>
</system.net>

Solution from proxy side, I faced some problems in the SSL handshake process and I had to force my proxy server to send requests using HTTP/1.0 to solve the problem by setting this argument in the httpd.conf SetEnv force-proxy-request-1.0 1 SetEnv proxy-nokeepalive 1 after that I faced the 417 error as my clients application was using HTTP/1.1 and the proxy was forced to use HTTP/1.0, the problem was solved by setting this parameter in the httpd.conf on the proxy side RequestHeader unset Expect early without the need to change anything in the client side, hope this helps.

如果你正在使用“HttpClient”,并且你不想使用全局配置来影响你可以使用的所有程序:

 HttpClientHandler httpClientHandler = new HttpClientHandler();
 httpClient.DefaultRequestHeaders.ExpectContinue = false;

如果你正在使用“WebClient”,我认为你可以尝试删除这个头通过调用:

 var client = new WebClient();
 client.Headers.Remove(HttpRequestHeader.Expect);

在我的情况下,这个错误似乎只有在我客户的计算机有严格的防火墙策略时才会发生,防火墙策略阻止了我的程序与web服务通信。

所以我能找到的唯一解决方案是捕捉错误并通知用户手动更改防火墙设置。