2015-06-03 25 views
0

這段代碼被寫入以向服務發送請求並接收簡單的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

+2

看起來不錯。也許你打電話給這個功能兩次? –

+0

檢查你的代碼,看看你是否調用兩次函數。 – user1666620

+0

我已經在調試器中測試了帶有斷點的代碼。它只運行一次 – Saifee

回答

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 

閱讀這篇文章的Web客戶端,HttpClient的比較和HttpWebRequest的