简体   繁体   English

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

[英]Send HTTP command rapidly in Windows Phone 8.1

I have a Vu+ satellite box and I am developing a WP8.1 remotecontrol for the box. 我有一个Vu +卫星盒子,正在为盒子开发WP8.1遥控器。

The Vu+ box has a webservice and takes command like: http://192.168.1.11/web/remotecontrol?command= {0} Vu +框具有Web服务,并接受以下命令: http : //192.168.1.11/web/remotecontrol? command= {0}

My code is like this: 我的代码是这样的:

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

    }

But it seems that the connection does not close. 但是似乎连接没有关闭。 I can only send the same command one time and then have to wait a minute before sending the same command again. 我只能一次发送同一命令,然后必须等待一分钟,然后再次发送同一命令。 I can send multiple different commands in a row. 我可以连续发送多个不同的命令。

Any help on how to optimize this? 对如何优化它有帮助吗?

Instead of passing additional parameter in your url, you can turn off caching. 您可以关闭缓存,而不是在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));
        }

There's another solution for this caching problem. 对于此缓存问题,还有另一种解决方案。 You can override default httpClientHandler like this 您可以像这样覆盖默认的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);
    }
}

While initiating your httpClient, you can pass above handler to avoid caching issue 在启动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));
}

Source: https://stackoverflow.com/a/25613559/546896 资料来源: https : //stackoverflow.com/a/25613559/546896

Came up with ugly hack. 出现了丑陋的骇客。 I will try to see how I can implement headers, though. 我将尝试看看如何实现标头。

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

That way the same command don't get cached. 这样,相同的命令就不会被缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM