Как загрузить файл с вызовом POST во внешний API - PullRequest
0 голосов
/ 03 ноября 2019

Я пытаюсь интегрировать использование внешнего API для выполнения вызовов POST и GET с моим клиентским приложением C # WPF. https://developers.virustotal.com/reference.

Вот что у меня сейчас есть:

ScanPage.xaml.cs

private void browseFileButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "All files (*.*)|*.*";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (openFileDialog.ShowDialog() == true)
            {
                filePath = openFileDialog.FileName;
                fileLocation.Text = filePath;
            }
        }


private async void uploadFileButton_Click(object sender, RoutedEventArgs e)
        {
            if (filePath != null)
            {
                var resultInfo = await InfoProcessor.PostInfo(filePath);
                responseText.Text = "File queued for scanning, please wait a moment...";
                var resultInfo2 = await InfoProcessor.LoadInfo(resultInfo.Resource);
                System.Threading.Thread.Sleep(10000);
                //await Task.Delay(5000).ContinueWith(t => runLoadInfo(resultInfo.Resource));
                responseText.Text = $"Scan Completed, MD5 checksum of file is {resultInfo2.Sha256} \n {resultInfo2.Positives} out of {resultInfo2.Total} {resultInfo2.Permalink} scan engines has detected to be potentially malicious";
            }
            else
            {
                MessageBox.Show("please upload a file");
            }
        }

public static async Task<InfoModel> PostInfo(string fileString)
        {
            string url = "https://www.virustotal.com/vtapi/v2/file/scan";
            string apiKey = "xxxxxx";
            string uploadedFile = fileString;

            var values = new Dictionary<string, string>
            {
                { "apikey", apiKey },
                { "file", uploadedFile}
            };

            var content = new FormUrlEncodedContent(values);

            using (HttpResponseMessage response = await ApiStartup.ApiClient.PostAsync(url, content))
            {
                InfoModel info = await response.Content.ReadAsAsync<InfoModel>();
                return info;
            }


            //var response = await ApiStartup.ApiClient.PostAsync(url, content);
            //var responseString = await response.Content.ReadAsStringAsync();
            //HttpResponseMessage response = await ApiStartup.ApiClient.PostAsJsonAsync("apikey",apiKey );
            //response.EnsureSuccessStatusCode();
        }

public static async Task<InfoModel> LoadInfo(string infoVar)
        {
            string apiKey = "xxxxxxxx";
            //string resourceKey = "efbb7149e39e70c84fe72c6fe8cef5d379fe37e7238d19a8a4536fb2a3146aed"; 
            string resourceKey = infoVar;
            string url = $"https://www.virustotal.com/vtapi/v2/file/report?apikey={apiKey}&resource={resourceKey}";

            using (HttpResponseMessage response = await ApiStartup.ApiClient.GetAsync(url))
            {
                if (response.IsSuccessStatusCode)
                {
                    InfoModel info = await response.Content.ReadAsAsync<InfoModel>();

                    return info;
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }

После публикации и полученияВ результате отсканированного отчета о загруженном файле кажется, что я загружаю только строку пути к файлу, а не сам файл. Как я могу закодировать его, чтобы выбранный файл был правильно размещен? Спасибо.

1 Ответ

0 голосов
/ 03 ноября 2019

Что касается вашего последнего комментария, то да, вы должны использовать многочастную форму сообщения.

Вы можете реализовать ее самостоятельно или использовать внешнюю библиотеку, чтобы сделать это для вас, например, VirusTotalNet, как указано в комментариях. Если вы все еще хотите сделать это самостоятельно, вот код из этой библиотеки:

https://github.com/Genbox/VirusTotalNet/blob/master/src/VirusTotalNet/VirusTotal.cs#L162-L217

...