win10 UWP GET Post

win10 应用应该是要有访问网络,网络现在最多的是使用GET,Post,简单的使用,可以用网络的数据:获得博客的访问量。

在使用网络,我们需要设置Package.appxmanifest

网络请求使用GET,首先有要访问的网站

string url = "http://blog.csdn.net/lindexi_gd/article/details/50830924";
//url是我一篇博客,win10 UWP Hmac,我很多博客都是读书笔记

WebRequest是请求基类,需要使用WebRequest.Create(url);

request.Method = "GET";

UWP 的Header设置

 request.Headers["Cookie"] 

接受需要一个函数 AsyncCallback

private void response_callback(IAsyncResult result)

request.BeginGetResponse(response_callback, request);

response_callback接受信息HttpWebRequest http_web_request = (HttpWebRequest)result.AsyncState;

                WebResponse web_response = http_web_request.EndGetResponse(result);
                using (Stream stream = web_response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string content = reader.ReadToEnd(); 
                    }
                }

我们需要对content进行正则

正则可以看 正则快速

                        Regex regex = new Regex(@"<span class=""link_view"" title=""阅读次数"">(\d\d\d人阅读)</span>");
                        string str = regex.Match(content).Result("阅读:$1");
                        reminder(str);

如果使用UI,直接使用会出现

这里写图片描述

我们写函数

        private async void reminder(string str)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () =>
                {
                    tb.Text += str;
                });
        }

网络很容易就异常

catch (WebException e)
            {
                switch (e.Status)
                {
                    case WebExceptionStatus.CacheEntryNotFound:
                        break;
                    case WebExceptionStatus.ConnectFailure:
                        reminder("ConnectFailure:远程服务器连接失败");
                        break;
                    case WebExceptionStatus.ConnectionClosed:
                        break;
                    case WebExceptionStatus.KeepAliveFailure:
                        break;
                    case WebExceptionStatus.MessageLengthLimitExceeded:
                        reminder("MessageLengthLimitExceeded 网络请求消息长度受到限制");
                        break;
                    case WebExceptionStatus.NameResolutionFailure:
                        break;
                    case WebExceptionStatus.Pending:
                        reminder("Pending 内部异步挂起");
                        break;
                    case WebExceptionStatus.PipelineFailure:
                        break;
                    case WebExceptionStatus.ProtocolError:
                        break;
                    case WebExceptionStatus.ProxyNameResolutionFailure:
                        break;
                    case WebExceptionStatus.ReceiveFailure:
                        break;
                    case WebExceptionStatus.RequestCanceled:
                        break;
                    case WebExceptionStatus.RequestProhibitedByCachePolicy:
                        break;
                    case WebExceptionStatus.RequestProhibitedByProxy:
                        break;
                    case WebExceptionStatus.SecureChannelFailure:
                        break;
                    case WebExceptionStatus.SendFailure:
                        break;
                    case WebExceptionStatus.ServerProtocolViolation:
                        break;
                    case WebExceptionStatus.Success:
                        break;
                    case WebExceptionStatus.Timeout:
                        break;
                    case WebExceptionStatus.TrustFailure:
                        break;
                    case WebExceptionStatus.UnknownError:
                        break;
                }
                reminder(e.Message);
            }

post需要把request.Method = "POST";

传输在request.BeginGetRequestStream(respeonse_streamCallback, request);

        private void respeonse_streamCallback(IAsyncResult result)
        {
            HttpWebRequest http_web_request = (HttpWebRequest) result.AsyncState;
            using (Stream stream=http_web_request.EndGetRequestStream(result))
            {
                //发送byte
                string str = "c";
                byte[] buffer = Encoding.UTF8.GetBytes(str);
                stream.Write(buffer,0,buffer.Length);
            }
            http_web_request.BeginGetResponse(response_callback, http_web_request);
        }

简单方法

            HttpClient http=new HttpClient();
            reminder(await http.GetStringAsync(new Uri(url)));

获整个对象

            HttpResponseMessage response = await http.GetAsync(new Uri(url));
            reminder(await response.Content.ReadAsStringAsync());
            HttpClient http = new HttpClient();
            HttpStringContent http_string =new HttpStringContent("a");
            HttpResponseMessage response = await http.PostAsync(new Uri(url), http_string);
            string str = await response.Content.ReadAsStringAsync();
            reminder(str);
            HttpClient http = new HttpClient();
            InMemoryRandomAccessStream memory =new InMemoryRandomAccessStream();
            HttpStreamContent stream=new HttpStreamContent(memory);
            HttpResponseMessage response = await http.PostAsync(new Uri(url), stream);
            string str = await response.Content.ReadAsStringAsync();
            reminder(str);
            HttpClient http = new HttpClient();
            InMemoryRandomAccessStream memory = new InMemoryRandomAccessStream();
            HttpStreamContent stream = new HttpStreamContent(memory);
            HttpRequestMessage request=new HttpRequestMessage(HttpMethod.Post,new Uri(url));
            request.Content = stream;
            HttpResponseMessage response = await http.SendRequestAsync(request);
            string str = await response.Content.ReadAsStringAsync();

看到有人说CSDN博客访问统计是Cache,如果我们要有很多访问,可以使用

filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
await Task.Run(() =>
            {
                reminder("\n");
                WebRequest request = WebRequest.Create(url);
                request.Method = "GET";
                request.Headers["Cookie"] = string.Empty;
                request.BeginGetResponse(response_callback, request);
            });

这里写图片描述

我把之前写的一个刷500

cookie可以使用HttpBaseProtocolFilter

设置cookie

            HttpCookie cookie = new HttpCookie("名称", "blog.csdn.net", "/")
            {
                Value = "a",
            };
            filter.CookieManager.SetCookie(cookie, false);

这写的不好,我将会写网络编程,这一篇会写容易的我的博客授权发在win10.me

原文:http://www.cnblogs.com/linzheng/

博客:blog.csdn.net/lindexi_gd

lindexi_gd CSDN认证博客专家 C# WPF UWP 微软最具价值专家
我是微软Windows应用开发方向的最具价值专家,欢迎访问我博客blog.lindexi.com里面有大量WPF和UWP博客
已标记关键词 清除标记
相关推荐
<div class="post-text" itemprop="text"> <p>So I need a progressbar on my application and I copied Microsoft's open source example (sorry not sorry), and it works amazing, except if you have to include POST data (or I'm just an idiot and can't figure it out.</p> <p>Working code:</p> <pre><code>const uint streamLength = 100000; HttpStreamContent streamContent = new HttpStreamContent(new SlowInputStream(streamLength)); IProgress<HttpProgress> progress = new Progress<HttpProgress>(ProgressHandler); response = await httpClient.PostAsync(new Uri(settings.url + "/script.php"), streamContent).AsTask(cts.Token, progress); </code></pre> <p>That gives me my progress and everything, now I need to add 4 post values, before I had them in a dictionary like so:</p> <pre><code>var values = new Dictionary<string, string> { { "1", "1" }, { "2", "2" }, { "3", "3" }, { "4", "4" } }; </code></pre> <p>Then I encoded them</p> <pre><code>HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(values); </code></pre> <p>How would I get my formContent (or if you want to do it another way, that works too) into the streamContent, because it looks like without the streamContent, that the progress does not work.</p> <p>Edit 1:</p> <p>So, it works, now the progress does not work anymore. Here Is my progress function</p> <pre><code>private void ProgressHandler(HttpProgress progress) { Debug.WriteLine("Stage: " + progress.Stage.ToString()); Debug.WriteLine("Retires: " + progress.Retries.ToString(CultureInfo.InvariantCulture)); Debug.WriteLine("Bytes Sent: " + progress.BytesSent.ToString(CultureInfo.InvariantCulture)); Debug.WriteLine("Bytes Received: " + progress.BytesReceived.ToString(CultureInfo.InvariantCulture)); ulong totalBytesToSend = 0; if (progress.TotalBytesToSend.HasValue) { totalBytesToSend = progress.TotalBytesToSend.Value; Debug.WriteLine("Total Bytes To Send: " + totalBytesToSend.ToString(CultureInfo.InvariantCulture)); } else { Debug.WriteLine("Total Bytes To Send: " + "unknown"); } ulong totalBytesToReceive = 0; if (progress.TotalBytesToReceive.HasValue) { totalBytesToReceive = progress.TotalBytesToReceive.Value; Debug.WriteLine("Total Bytes To Receive: " + totalBytesToReceive.ToString(CultureInfo.InvariantCulture)); } else { Debug.WriteLine("Total Bytes To Receive: " + "unknown"); } double requestProgress = 0; if (progress.Stage == HttpProgressStage.SendingContent && totalBytesToSend > 0) { requestProgress = progress.BytesSent * 50 / totalBytesToSend; } else if (progress.Stage == HttpProgressStage.ReceivingContent) { // Start with 50 percent, request content was already sent. requestProgress += 50; if (totalBytesToReceive > 0) { requestProgress += progress.BytesReceived * 50 / totalBytesToReceive; } } else { return; } Debug.WriteLine("Progress: " + requestProgress); snap_progress.Value = requestProgress; } </code></pre> <p>And here is what it shows in debug:</p> <pre><code>Stage: ReceivingContent Retires: 0 Bytes Sent: 180 Bytes Received: 6757607 Total Bytes To Send: 180 Total Bytes To Receive: unknown Progress: 50 </code></pre> <p>It is at unknown the entire time even though I see Bytes Received increasing.</p> </div>
©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页