簡體   English   中英

在Windows Phone 8.1中快速發送HTTP命令

[英]Send HTTP command rapidly in Windows Phone 8.1

我有一個Vu +衛星盒子,正在為盒子開發WP8.1遙控器。

Vu +框具有Web服務,並接受以下命令: http : //192.168.1.11/web/remotecontrol? command= {0}

我的代碼是這樣的:

  private void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            string cmd = ((Button)sender).Tag.ToString();
            SendBtnCommand(cmd);
        }
        catch { }

    }

    private async void SendBtnCommand(string cmd)
    {
        using (HttpClient h = new HttpClient())
        {
            string x = await h.GetStringAsync(string.Format("http://192.168.1.11/web/remotecontrol?command={0}", cmd));
        }

    }

但是似乎連接沒有關閉。 我只能一次發送同一命令,然后必須等待一分鍾,然后再次發送同一命令。 我可以連續發送多個不同的命令。

對如何優化它有幫助嗎?

您可以關閉緩存,而不是在URL中傳遞其他參數。

using (var h = new HttpClient())
        {
            h.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue {NoCache = true};
            string x = await h.GetStringAsync(string.Format("http://192.168.1.11/web/remotecontrol?command={0}", cmd));
        }

對於此緩存問題,還有另一種解決方案。 您可以像這樣覆蓋默認的httpClientHandler

public class BypassCacheHttpRequestHandler : HttpClientHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Headers.IfModifiedSince == null)
            request.Headers.IfModifiedSince = new DateTimeOffset(DateTime.Now);
        return base.SendAsync(request, cancellationToken);
    }
}

在啟動httpClient時,您可以傳遞上述處理程序以避免緩存問題

using (var h = new HttpClient((new BypassCacheHttpRequestHandler(), true))
{
 string x =await h.GetStringAsync(string.Format("http://192.168.1.11/web/remotecontrol?command={0}", cmd));
}

資料來源: https : //stackoverflow.com/a/25613559/546896

出現了丑陋的駭客。 我將嘗試看看如何實現標頭。

string x = await h.GetStringAsync(string.Format("http://192.168.1.11/web/remotecontrol?command={0}&amp;{1}", cmd, DateTime.Now.Millisecond));

這樣,相同的命令就不會被緩存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM