为什么它发出两次请求

why is it making the request twice

编写此代码是为了向服务发送请求并接收简单的 json 响应,但服务的服务器日志显示它被请求两次,延迟为 1 秒。我不明白为什么这段代码会发出两次请求,如果缺少某些配置,请指导我。

string StrUrl = @"http://www.myapp.com/Tracker.json";
Uri uri1 = new Uri(StrUrl);
HttpWebRequest webRequest1 = (HttpWebRequest)HttpWebRequest.Create(uri1);
webRequest1.ServicePoint.ConnectionLimit = 1;
webRequest1.Timeout = 50000;
webRequest1.ReadWriteTimeout = 50000
webRequest1.PreAuthenticate = false;
webRequest1.Proxy = null;
webRequest1.CookieContainer = cookieJar;
webRequest1.Method = "POST";
webRequest1.KeepAlive = false;

WebResponse response1 = webRequest1.GetResponse();

StreamReader streamReader1 = new StreamReader(response1.GetResponseStream());
String responseData1 = streamReader1.ReadToEnd();

这些可能是类似的问题

https://social.msdn.microsoft.com/Forums/vstudio/en-US/dad87752-42dd-4346-a1c5-da30f6156406/why-httpwebrequest-send-data-twice-in-https

使用RestSharp (Simple REST and HTTP API Client for .NET)解决了这个问题。

var client = new RestClient("http://www.myapp.com/Tracker.json");
// client.Authenticator = new HttpBasicAuthenticator(username, password);

var request = new RestRequest("", Method.POST);

// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string

阅读本文以比较 WebClient、HttpClient 和 HttpWebRequest