UWP模拟获取验证码

2018年4月24日 0 作者 snowysong@live.com
阅读需要1分钟

0x00.添加引用

using System.Threading.Tasks;
using System.Net.Http;

0x01.创建新Task

public static Task<HttpResponseMessage> VerCode(string Req)//Req为获取验证码的请求连接,可去需要的网站分析请求获取
{
    return Task.Run(() =>
    {
        HttpClient request = new HttpClient(HttpClientHandler);
        HttpResponseMessage response;
        {
            request.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
            request.DefaultRequestHeaders.Add("Accept", "*/*");
            request.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
            request.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
        }//模拟请求头
        try
        {
            response = request.GetAsync(Req).Result;//响应内容为MIME
        }
        catch
        {
            response = null;
        }
        return response;
    });
}

0x02.流形式读取

private async Task GetVerCodeAsync(string Req)//Req为获取验证码的请求连接,可去需要的网站分析请求获取
{
    HttpResponseMessage response = await Sign.VerCode(Req);
    byte[] streamByte = response.Content.ReadAsByteArrayAsync().Result;
    MemoryStream ms = new MemoryStream(streamByte);
    BitmapImage img = new BitmapImage();
    await img.SetSourceAsync(ms.AsRandomAccessStream());//img为Image控件
    VerCodeImg.Source = img;
}

0x03.点击刷新(因网站而异)

private async void VerCodeBtn_Click(object sender, RoutedEventArgs e)
{
    a = a + 1;
    string plus = "?test=" + a;
    string baseReq = "https://www.sonystyle.com.cn/mysony/campaign/api/captcha.do" + plus;
    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
    {
        await GetVerCodeAsync(baseReq);
    });
}

0x04.相关

MIME 参考手册

0 0 vote
Article Rating