Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# UWP如何从我的web api下载图像?_C#_Asp.net Core_Uwp_Httpclient - Fatal编程技术网

C# UWP如何从我的web api下载图像?

C# UWP如何从我的web api下载图像?,c#,asp.net-core,uwp,httpclient,C#,Asp.net Core,Uwp,Httpclient,我有一个.NET核心Web应用程序,它在wwwroot文件夹中存储不同的目录 我想知道如何使用HttpClientAPI从我的UWP应用程序下载这些照片。提前谢谢 我的意思是如何在UWP中实现代码,以便使用HttpClient下载这些文件 您可以使用HttpClient从服务器下载流。下面的段代码源于官方代码示例 private async void Start_Click(object sender, RoutedEventArgs e) { Uri resourceAddress;

我有一个.NET核心Web应用程序,它在wwwroot文件夹中存储不同的目录

我想知道如何使用
HttpClient
API从我的UWP应用程序下载这些照片。提前谢谢


我的意思是如何在UWP中实现代码,以便使用HttpClient下载这些文件

您可以使用
HttpClient
从服务器下载流。下面的段代码源于官方代码示例

private async void Start_Click(object sender, RoutedEventArgs e)
{
    Uri resourceAddress;

    // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
    // valid, absolute URI, we'll notify the user about the incorrect input.
    if (!Helpers.TryGetUri(AddressField.Text, out resourceAddress))
    {
        rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
        return;
    }

    Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
    rootPage.NotifyUser("In progress", NotifyType.StatusMessage);

    try
    {
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);

        // Do not buffer the response.
        HttpResponseMessage response = await httpClient.SendRequestAsync(
            request,
            HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);

        OutputField.Text += Helpers.SerializeHeaders(response);

        StringBuilder responseBody = new StringBuilder();
        using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
        {
            int read = 0;
            byte[] responseBytes = new byte[1000];
            do
            {
                read = await responseStream.ReadAsync(responseBytes, 0, responseBytes.Length);

                responseBody.AppendFormat("Bytes read from stream: {0}", read);
                responseBody.AppendLine();

                // Use the buffer contents for something. We can't safely display it as a string though, since encodings
                // like UTF-8 and UTF-16 have a variable number of bytes per character and so the last bytes in the buffer
                // may not contain a whole character. Instead, we'll convert the bytes to hex and display the result.
                IBuffer responseBuffer = CryptographicBuffer.CreateFromByteArray(responseBytes);
                responseBuffer.Length = (uint)read;
                responseBody.AppendFormat(CryptographicBuffer.EncodeToHexString(responseBuffer));
                responseBody.AppendLine();
            } while (read != 0);
        }
        OutputField.Text += responseBody.ToString();

        rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
    }
    catch (TaskCanceledException)
    {
        rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
    }
    catch (Exception ex)
    {
        rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);
    }
    finally
    {
        Helpers.ScenarioCompleted(StartButton, CancelButton);
    }
}
你也可以用它来实现这一点。这是我的


我的意思是如何在UWP中实现代码以使用HttpClientYou need URI下载这些文件,然后您可以按照下面的答案进行操作,如果下面的答案解决了您的问题,请稍后访问此线程的方便用户接受,谢谢理解。
private async void StartDownload(BackgroundTransferPriority priority)
{
    // Validating the URI is required since it was received from an untrusted source (user input).
    // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
    // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
    // the "Home or Work Networking" capability.
    Uri source;
    if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out source))
    {
        rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
        return;
    }

    string destination = fileNameField.Text.Trim();

    if (string.IsNullOrWhiteSpace(destination))
    {
        rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage);
        return;
    }

    StorageFile destinationFile;
    try
    {
        destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
            destination,
            CreationCollisionOption.GenerateUniqueName);
    }
    catch (FileNotFoundException ex)
    {
        rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage);
        return;
    }

    BackgroundDownloader downloader = new BackgroundDownloader();
    DownloadOperation download = downloader.CreateDownload(source, destinationFile);

    Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}",
        source.AbsoluteUri, destinationFile.Name, priority, download.Guid));

    download.Priority = priority;

    // Attach progress and completion handlers.
    await HandleDownloadAsync(download, true);
}