why is it making the request twice

2019-06-14 14:02发布

问题:

this code is written to send request to a service and receive simple json response but the service's server log shows that it is being requested twice with a delay of 1 second. I cant figure it out why does this code make the request twice please guide me if there is some configuration missing.

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();

these might be similar problems

Why my Http client making 2 requests when I specify credentials?

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

回答1:

this problem solved by using 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

read this article for comparison of WebClient, HttpClient and HttpWebRequest