【原创】请求时发生417错误
最近在工作中遇见一个奇怪的问题,有一段程序是需要跟别的公司的程序做段交互。
开发环境:VS.NET2003 WINDOWS SERVER 2003 IIS5 Framework1.1
症状:这段代码在测试平台没有问题,发布到正式平台后,发现报告异常: 417 Expectation Failed
示例代码如下:
Code
try
{
WebRequest req;
req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
Response.Write(url + "<br/>");
ASCIIEncoding enc = new ASCIIEncoding();
Byte[] buf;
buf = enc.GetBytes("CLIENT_ID=" + clienId + "&B_IP=" + c_b_ip);
Response.Write(clienId + "." + c_b_ip + "<br/>");
Stream news;
news = req.GetRequestStream();
news.Write(buf, 0, buf.Length);
news.Close();
Response.Write("Here1<br/>");
WebResponse res;
res = req.GetResponse();
Response.Write("Here2<br/>");
StreamReader sr;
sr = new StreamReader(res.GetResponseStream());
Response.Write("Here3<br/>");
char[] buff = new char[4096];
int count= sr.Read(buff,0,4096);
string red;
red = "";
while(count > 0)
{
string s = new string(buff, 0, count);
Response.Write(s + "\r\n");
red = red + s;
count = sr.Read(buff, 0, 4096);
}
sr.Close();
res.Close();
return red;
}
catch(Exception ex)
{
Response.Write("错误信息:"+ex);
return "-1";
}
Code
string r_code;
r_code = GetRandomCode("http://www.cnblogs.com/A_B_random_code.jsp", "CER_KEY","101.11.1.1");
string redirectURL;
string userName;
userName = "zhuanjia1";
redirectURL = "http://www.cnblogs.com/A_B_random_redirect.jsp?un=" + userName + "&r_code=" + r_code;
Response.Write(redirectURL);
http://www.cnblogs.com/login.jsp<br/>
cnblogs.172.0.0.1<br/>
Here1<br/>
错误信息:System.Net.WebException:远程服务器返回错误:<417>Expectation Failed。
as System.Net.HttpWebRequest.CheckFinalStatus<>
as System.Net.HttpWebRequest.EndGetResponse<IAsyncResult asyncResult>
as System.Net.HttpWebRequest.GetResponse<>
http://www.cnblogs.com/login.jsp<br/>
cnblogs.172.0.0.1<br/>
Here1<br/>
Here2<br/>
Here3<br/>
在第一段代码中加入如下一句,问题解决:
System.Net.ServicePointManager.Expect100Continue = false;
或在配置文件中加入:
<configuration>
<system.net> <system.net>
<settings> <settings>
<servicePointManager expect100Continue="false" />
这个异常源自HTTP1.1协议的一个规范: 100(Continue)
100(Continue)状态代码的解释
允许客户端发request消息body之前先用request header试探一下server,看server要不要接收request body,再决定要不要发request body。
客户端在Request头部中包含
Expect:100-continue
Server接到后 如果回100(continue)这个状态代码,客户端就继续发request body。
这个设置是Http1.1才有。