UWP模拟获取验证码

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 参考手册

C# 模拟POST上传图片至服务器

0x00.添加引用

using System;
using System.IO;
using System.Net.Http.Headers;
using System.ComponentModel;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml.Media.Imaging;

 


0x01.选择文件

        List<UploadImageInfo> imginfo = new List<UploadImageInfo>();
        private async void SelectFiles_Click(object sender, RoutedEventArgs e)
        {          
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");

            var files = await openPicker.PickMultipleFilesAsync();//选择多个文件

            foreach (StorageFile sf in files)
            {
                tokenInfo = await TokenInfo.GetTokenAsync();//自定义获取token函数
                UploadImageInfo uploadImages = new UploadImageInfo();//自定义图片类
                BitmapImage bitmap = new BitmapImage();
                using (var stream = await sf.OpenAsync(FileAccessMode.ReadWrite))
                {
                    bitmap.SetSource(stream);
                    if (stream.Size < 1024 * 1024)
                    {
                        uploadImages.DataSize = Math.Round((double)stream.Size / 1024, 2).ToString ()+"  Kb";
                    }
                    else
                    {
                        uploadImages.DataSize = Math.Round((double)stream.Size / 1024 / 1024, 2).ToString()+"  Mb";
                    }
                    Stream s = WindowsRuntimeStreamExtensions.AsStreamForRead(stream.GetInputStreamAt(0));
                    uploadImages.ContentByte = ConvertStreamTobyte(s);
                    s.Close();//务必结束,否则文件会一直被占用。
                }

                uploadImages.Content = bitmap;
                uploadImages.Name = sf.Name;
                uploadImages.DateCreated = sf.DateCreated.ToString();
                uploadImages.Cameras = cameras;
                uploadImages.Lens = lens;
                imginfo.Add(uploadImages);
}

0x02.异步上传

public static async Task<string> UploadFilesAsync(UploadImageInfo uploadImageInfo, string uzrtoken, string uploadtoken, string userId, string campaignId)
{
   HttpClientHandler handler = new HttpClientHandler();
   HttpClient httpClient = new HttpClient(Sign.HttpClientHandler);
   httpClient.DefaultRequestHeaders.Accept.ParseAdd("text/*");
   httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd("Shockwave Flash");

   HttpResponseMessage response = new HttpResponseMessage();
   var content = new MultipartFormDataContent();//使用MultipartFormDataContent进行form-data请求头封装
   var contentByteContent = new ByteArrayContent(uploadImageInfo.ContentByte);
   contentByteContent.Headers.Add("Content-Type", "application/octet-stream");
   contentByteContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
   contentByteContent.Headers.ContentDisposition.FileName = "\"" + uploadImageInfo.Name + "\"";
   contentByteContent.Headers.ContentDisposition.Name = "\"imagefile\"";//封装POST请求头
    {
      content.Add(new StringContent(uploadImageInfo.Name), "\"Filename\"");
      content.Add(new StringContent("1"), "\"uploadTokenType\"");
      content.Add(new StringContent("0"), "\"fileType\"");
      content.Add(new StringContent(uploadImageInfo.Name), "\"title\"");
      content.Add(new StringContent("2"), "\"userTokenType\"");
      content.Add(new StringContent(campaignId), "\"campaignId\"");
      content.Add(new StringContent(userId), "\"userId\"");
      content.Add(new StringContent(uploadtoken), "\"uploadToken\"");
      content.Add(new StringContent(uzrtoken), "\"userToken\"");
      content.Add(contentByteContent, "\"imagefile\"");
      content.Add(new StringContent("Submit Query"), "\"Upload\"");
    }

   response = await httpClient.PostAsync(new Uri("http://media.sony.com.cn/alphacafe/upload", UriKind.Absolute), content);
   string sid = response.Content.ReadAsStringAsync().Result;
   
   if (response.IsSuccessStatusCode&&sid.Contains("fileID")==true)
    {
      string s = response.Content.ReadAsStringAsync().Result.Split('"')[7];
      return s;
    }
   else return "failed";
}



0x03.上传

private async void Submit_Click(object sender, RoutedEventArgs e)
{
  foreach (UploadImageInfo item in imgitems)
   {
    string fileId = await UploadImageInfo.UploadFilesAsync(item, tokenInfo.userToken, tokenInfo.upLoadToken, userId, "16");
    if (fileId.Contains("failed") == false)
     {
      item.FileID.Insert(0, fileId);//上传成功则返回文件Id
     }
   }
}