UWP——HttpClient模拟浏览器的GET、POST请求

这里再插一篇——HttpClient模拟浏览器的GET、POST请求。这也是我的第一个UWP应用程序。这一篇和上一篇类似,只不过将HttpWebRequest换成了HttpClient。我们还是先看一下修改之前的数据,截图如下:


之后,我们还是点击【编辑】,并利用Fiddler监测请求数据。截图这里不用了,和上一篇中一样。下面我们先看一下在UWP程序中利用HttpClient的Get代码:

        private void btnGet_Click(object sender, RoutedEventArgs e)
        {
            GetRequestVerificationToken();
        }

        private async void GetRequestVerificationToken()
        {
            Loading1.IsActive = true;
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync("http://192.168.1.105/Movies/Edit/6");
                    if (response.EnsureSuccessStatusCode().StatusCode.ToString().ToLower() == "ok")
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        //以下通过 正则表达式 查到隐藏域 name='__RequestVerificationToken'
                        //为稍后的POST请求使用
                        string patternRegion = "<\\s*input\\s*.*name\\s*=\\s*\"__RequestVerificationToken\"\\s*.*value\\s*=\\s*\"(?<value>[\\w-]{108,108})\"\\s*/>";
                        RegexOptions regexOptions = RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled;
                        Regex reg = new Regex(patternRegion, regexOptions);
                        MatchCollection mc = reg.Matches(responseBody);
                        foreach (Match m in mc)
                        {
                            hidRequestVerificationToken = m.Groups["value"].Value;
                        }
                        WebView1.NavigateToString(responseBody);
                    }
                }
                catch (HttpRequestException ex)
                {
                    await new MessageDialog(ex.Message).ShowAsync();
                }
            }
            Loading1.IsActive = false;
        }
再看一下,程序截图:


这里我们不难发现这个Get请求很简单—不用设置HTTP头部信息(当然你也设置,有很多教程)。哈哈,重要的是不用设置Cookie。在相应的时候,这里也没有处理编码,不知道是不是所有的都是这样。下面看一下POST修改请求的代码:

        private async void btnPost_Click(object sender, RoutedEventArgs e)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var kvp = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string,string>("__RequestVerificationToken", hidRequestVerificationToken),
                        new KeyValuePair<string,string>("ID", "6"),
                        new KeyValuePair<string,string>("Title", "速度与激情6"),
                        new KeyValuePair<string,string>("ReleaseDate", "2013-05-24"),
                        new KeyValuePair<string,string>("Genre", "动作 犯罪 剧情 冒险"),
                        new KeyValuePair<string,string>("Price", "35")
                    };
                    HttpResponseMessage response = await client.PostAsync("http://192.168.1.105/Movies/Edit/6", new FormUrlEncodedContent(kvp));
                    if (response.EnsureSuccessStatusCode().StatusCode.ToString().ToLower() == "ok")
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        WebView1.NavigateToString(responseBody);
                    }
                }
                catch (HttpRequestException ex)
                {
                    await new MessageDialog(ex.Message).ShowAsync();
                }
            }
        }
现在我们点击【POST】按钮,看看效果:


现在我们刷新一下页面看看情况:


在代码中我们不难看出,这次POST请求并没有处理Cookie。这是我感觉最爽的地方!在下一篇,希望可以部署在手机上,想看一下UWP是怎么通用的。最后看一下代码结构以及XAML前台代码:


前台代码:

<Page
    x:Class="DDZ.UWP1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DDZ.UWP1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="50"></RowDefinition>
            <RowDefinition Height="50"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        
        <Button x:Name="btnGet" Content="Get" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" Click="btnGet_Click"/>
        <Button x:Name="btnPost" Content="Post" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Click="btnPost_Click"/>
        <Button x:Name="btnTurnPage" Content="跳转" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Row="1" Grid.ColumnSpan="2" Margin="20,0,20,0" Click="btnTurnPage_Click"/>
        <WebView x:Name="WebView1" Grid.Row="2" Grid.ColumnSpan="2"/>
        <ProgressRing x:Name="Loading1" Height="50" Width="50" Canvas.ZIndex="100" Grid.Row="2" Grid.ColumnSpan="2"/>
    </Grid>
</Page>
这篇就写到这里了,希望前辈多多指点,谢谢!


展开阅读全文

没有更多推荐了,返回首页