C# WebApi遇到的坑之第二次请求失败问题
标签:null str timeout bre buffer urlencode 代码 utf8 pre
最近做的一个WebApi项目,需要访问别人的接口。写好访问POST请求的接口后,调试成功!
But,第二次请求就会超时!Why???
于是乎网上各种找方案,无奈就是找不到。怎么办呢?于是把HttpWebRequest类的每一个属性都设置一边看看有没有效果。
皇天不负有心人啊,终于找到了病症的症结所在····
不废话了,贴代码:
1 ///
2 /// POST请求
3 ///
4 /// 地址
5 /// 参数
6 /// 超时时间
7 ///
8 public static string HttpPost(string url, IDictionarystring, string> parameters, int timeOut)
9 {
10 HttpWebRequest request = null;
11 request = WebRequest.Create(url) as HttpWebRequest;
12 request.Method = "POST";
13 request.ContentType = "application/x-www-form-urlencoded";
14 request.Timeout = timeOut;//超时时间
15 request.ServicePoint.Expect100Continue = false;//解决第二次请求失败问题
16
17 //发送POST数据
18 if (!(parameters == null || parameters.Count == 0))
19 {
20 StringBuilder buffer = new StringBuilder();
21 int i = 0;
22 foreach (string key in parameters.Keys)
23 {
24 if (i > 0)
25 {
26 buffer.AppendFormat("&{0}={1}", key, parameters[key]);
27 }
28 else
29 {
30 buffer.AppendFormat("{0}={1}", key, parameters[key]);
31 i++;
32 }
33 }
34 byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
35 using (Stream stream = request.GetRequestStream())
36 {
37 stream.Write(data, 0, data.Length);
38 }
39 }
40 string[] values = request.Headers.GetValues("Content-Type");
41
42 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
43
44 using (Stream s = response.GetResponseStream())
45 {
46 StreamReader reader = new StreamReader(s, Encoding.UTF8);
47 return reader.ReadToEnd();
48 }
49 }
关键点就在于设置一个属性为false:request.ServicePoint.Expect100Continue = false;
C# WebApi遇到的坑之第二次请求失败问题
标签:null str timeout bre buffer urlencode 代码 utf8 pre
原文地址:https://www.cnblogs.com/xujingdong/p/9054733.html
评论