为什么要两次提出请求

时间:2015-06-03 10:32:19

标签: c# asp.net http httpwebrequest

编写此代码是为了向服务发送请求并接收简单的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();

这些可能是类似的问题

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 个答案:

答案 0 :(得分:0)

使用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