HttpClient

Önemli API'ler

HTTP 2.0 ve HTTP 1.1 protokollerini kullanarak bilgi göndermek ve almak için HttpClient ve Windows.Web.Http ad alanı API'sinin geri kalanını kullanın.

Tavsiye

.NET 6 veya sonraki sürümleri hedefleyen WinUI 3 uygulamaları, System.Net.Http.HttpClient öğesini de kullanabilir (.NET HttpClient’i). IHttpClientFactory, iptal belirteçlerini ve modern eşzamansız programlama kalıplarını destekler. Kimlik bilgisi istemleri, WinRT aracısı üzerinden tanımlama bilgisi yönetimi veya Windows ağ yalıtımıyla tümleştirme gibi WinRT'ye özgü özelliklere ihtiyaç duyduğunuzda Windows.Web.Http.HttpClient kullanın. bir .NET WinUI 3 uygulamasındaki basit HTTP istekleri için genellikle System.Net.Http.HttpClient daha basittir.

HttpClient ve Windows.Web.Http ad alanına genel bakış

Windows sınıflar. Web.Http ad alanı ve ilgili Windows. Web.Http.Headers ve Windows. Web.Http.Filters ad alanları, temel GET isteklerini gerçekleştirmek veya aşağıda listelenen daha gelişmiş HTTP işlevselliğini uygulamak üzere HTTP istemcisi işlevi görür Windows uygulamalar için bir programlama arabirimi sağlar.

  • Yaygın fiiller için yöntemler (DELETE, GET, PUT ve POST). Bu isteklerin her biri zaman uyumsuz bir işlem olarak gönderilir.

  • Yaygın kimlik doğrulama ayarları ve düzenleri için destek.

  • Aktarımdaki Güvenli Yuva Katmanı (SSL) ayrıntılarına erişim.

  • Gelişmiş uygulamalara özelleştirilmiş filtreler ekleme olanağı.

  • Tanımlama bilgilerini alma, ayarlama ve silme olanağı.

  • HTTP İsteği ilerleme durumu bilgileri zaman uyumsuz yöntemlerde kullanılabilir.

Windows. Web.Http.HttpRequestMessage sınıfı, Windows tarafından gönderilen bir HTTP isteği iletisini temsil eder. Web.Http.HttpClient. Windows. Web.Http.HttpResponseMessage sınıfı, bir HTTP isteğinden alınan HTTP yanıt iletisini temsil eder. HTTP iletileri RFC 2616'da IETF tarafından tanımlanır.

Windows.Web.Http ad alanı, HTTP içeriğini, tanımlama bilgileri dahil olmak üzere HTTP varlık gövdesi ve üst bilgileri olarak temsil eder. HTTP içeriği bir HTTP isteği veya HTTP yanıtıyla ilişkilendirilebilir. Windows. Web.Http ad alanı, HTTP içeriğini temsil eden bir dizi farklı sınıf sağlar.

"HTTP üzerinden basit bir GET isteği gönder" bölümündeki kod parçacığı, HTTP GET isteğinden gelen HTTP yanıtını dize olarak göstermek için HttpStringContent sınıfını kullanır.

Windows.Web.Http.Headers ad alanı, HTTP üst bilgilerinin ve tanımlama bilgilerinin oluşturulmasını ve bunların HttpRequestMessage ve HttpResponseMessage nesnelerinin özellikleri olarak ilişkilendirilmesini destekler.

HTTP üzerinden basit bir GET isteği gönderme

Bu makalenin önceki bölümlerinde belirtildiği gibi Windows. Web.Http ad alanı, Windows uygulamaların GET istekleri göndermesine olanak tanır. Aşağıdaki kod parçacığı, http://www.contoso.com sınıfını kullanarak öğesine nasıl GET isteği gönderileceğini ve GET isteğinin yanıtını okumak için Windows.Web.Http.HttpResponseMessage sınıfının nasıl kullanılacağını gösterir.

//Create an HTTP client object
Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

//Add a user-agent header to the GET request.
var headers = httpClient.DefaultRequestHeaders;

//The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
//especially if the header value is coming from user input.
string header = "MyApp/1.0";
if (!headers.UserAgent.TryParseAdd(header))
{
    throw new Exception("Invalid header value: " + header);
}

Uri requestUri = new Uri("https://www.contoso.com");

//Send the GET request asynchronously and retrieve the response as a string.
Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
string httpResponseBody = "";

try
{
    //Send the GET request
    httpResponse = await httpClient.GetAsync(requestUri);
    httpResponse.EnsureSuccessStatusCode();
    httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
    httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}
// pch.h
#pragma once
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Web.Http.Headers.h>

// main.cpp : Defines the entry point for the console application.
#include "pch.h"
#include <iostream>
using namespace winrt;
using namespace Windows::Foundation;

int main()
{
    init_apartment();

    // Create an HttpClient object.
    Windows::Web::Http::HttpClient httpClient;

    // Add a user-agent header to the GET request.
    auto headers{ httpClient.DefaultRequestHeaders() };

    // The safe way to add a header value is to use the TryParseAdd method, and verify the return value is true.
    // This is especially important if the header value is coming from user input.
    std::wstring header{ L"MyApp/1.0" };
    if (!headers.UserAgent().TryParseAdd(header))
    {
        throw L"Invalid header value: " + header;
    }

    Uri requestUri{ L"https://www.contoso.com" };

    // Send the GET request asynchronously, and retrieve the response as a string.
    Windows::Web::Http::HttpResponseMessage httpResponseMessage;
    std::wstring httpResponseBody;

    try
    {
        // Send the GET request.
        httpResponseMessage = httpClient.GetAsync(requestUri).get();
        httpResponseMessage.EnsureSuccessStatusCode();
        httpResponseBody = httpResponseMessage.Content().ReadAsStringAsync().get();
    }
    catch (winrt::hresult_error const& ex)
    {
        httpResponseBody = ex.message();
    }
    std::wcout << httpResponseBody;
}

İkili verileri HTTP üzerinden POST et

Aşağıdaki C++/WinRT kod örneği, web sunucusuna dosya yükleme olarak az miktarda ikili veri göndermek için form verilerinin ve POST isteğinin kullanılmasını göstermektedir. Kod, ikili verileri temsil etmek için HttpBufferContent sınıfını ve çok parçalı form verilerini temsil etmek için HttpMultipartFormDataContent sınıfını kullanır.

Note

Get çağrısı (aşağıdaki kod örneğinde görüldüğü gibi) kullanıcı arabirimi iş parçacığı için uygun değildir. Bu durumda kullanılacak doğru teknik için bkz. C++/WinRT ile eşzamanlılık ve zaman uyumsuz işlemler.

// pch.h
#pragma once
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Security.Cryptography.h>
#include <winrt/Windows.Storage.Streams.h>
#include <winrt/Windows.Web.Http.Headers.h>

// main.cpp : Defines the entry point for the console application.
#include "pch.h"
#include <iostream>
#include <sstream>
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Storage::Streams;

int main()
{
    init_apartment();

    auto buffer{
        Windows::Security::Cryptography::CryptographicBuffer::ConvertStringToBinary(
            L"A sentence of text to encode into binary to serve as sample data.",
            Windows::Security::Cryptography::BinaryStringEncoding::Utf8
        )
    };
    Windows::Web::Http::HttpBufferContent binaryContent{ buffer };
    // You can use the 'image/jpeg' content type to represent any binary data;
    // it's not necessarily an image file.
    binaryContent.Headers().Append(L"Content-Type", L"image/jpeg");

    Windows::Web::Http::Headers::HttpContentDispositionHeaderValue disposition{ L"form-data" };
    binaryContent.Headers().ContentDisposition(disposition);
    // The 'name' directive contains the name of the form field representing the data.
    disposition.Name(L"fileForUpload");
    // Here, the 'filename' directive is used to indicate to the server a file name
    // to use to save the uploaded data.
    disposition.FileName(L"file.dat");

    Windows::Web::Http::HttpMultipartFormDataContent postContent;
    postContent.Add(binaryContent); // Add the binary data content as a part of the form data content.

    // Send the POST request asynchronously, and retrieve the response as a string.
    Windows::Web::Http::HttpResponseMessage httpResponseMessage;
    std::wstring httpResponseBody;

    try
    {
        // Send the POST request.
        Uri requestUri{ L"https://www.contoso.com/post" };
        Windows::Web::Http::HttpClient httpClient;
        httpResponseMessage = httpClient.PostAsync(requestUri, postContent).get();
        httpResponseMessage.EnsureSuccessStatusCode();
        httpResponseBody = httpResponseMessage.Content().ReadAsStringAsync().get();
    }
    catch (winrt::hresult_error const& ex)
    {
        httpResponseBody = ex.message();
    }
    std::wcout << httpResponseBody;
}

Gerçek bir ikili dosyanın içeriğini POST olarak göndermek için (yukarıda kullanılan açık ikili veriler yerine), HttpStreamContent nesnesini kullanmayı daha kolay bulacaksınız. Bir tane oluşturun ve oluşturucusuna bağımsız değişken olarak StorageFile.OpenReadAsync çağrısından döndürülen değeri geçirin. Bu yöntem, ikili dosyanızın içindeki veriler için bir akış döndürür.

Ayrıca, büyük bir dosyayı (yaklaşık 10 MB'tan büyük) karşıya yüklüyorsanız Windows Çalışma Zamanı Arka Plan Aktarımı API'lerini kullanmanızı öneririz.

HTTP üzerinden POST JSON verileri

Aşağıdaki örnek bir uç noktaya JSON gönderip yanıt gövdesini yazar.

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.Web.Http;

private async Task TryPostJsonAsync()
{
    try
    {
        // Construct the HttpClient and Uri. This endpoint is for test purposes only.
        HttpClient httpClient = new HttpClient();
        Uri uri = new Uri("https://www.contoso.com/post");

        // Construct the JSON to post.
        HttpStringContent content = new HttpStringContent(
            "{ \"firstName\": \"Eliot\" }",
            UnicodeEncoding.Utf8,
            "application/json");

        // Post the JSON and wait for a response.
        HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
            uri,
            content);

        // Make sure the post succeeded, and write out the response.
        httpResponseMessage.EnsureSuccessStatusCode();
        var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
        Debug.WriteLine(httpResponseBody);
    }
    catch (Exception ex)
    {
        // Write out any exceptions.
        Debug.WriteLine(ex);
    }
}
// pch.h
#pragma once
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Security.Cryptography.h>
#include <winrt/Windows.Storage.Streams.h>
#include <winrt/Windows.Web.Http.Headers.h>

// main.cpp : Defines the entry point for the console application.
#include "pch.h"
#include <iostream>
#include <sstream>
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Storage::Streams;

int main()
{
    init_apartment();

    Windows::Web::Http::HttpResponseMessage httpResponseMessage;
    std::wstring httpResponseBody;

    try
    {
        // Construct the HttpClient and Uri. This endpoint is for test purposes only.
        Windows::Web::Http::HttpClient httpClient;
        Uri requestUri{ L"https://www.contoso.com/post" };

        // Construct the JSON to post.
        Windows::Web::Http::HttpStringContent jsonContent(
            L"{ \"firstName\": \"Eliot\" }",
            UnicodeEncoding::Utf8,
            L"application/json");

        // Post the JSON, and wait for a response.
        httpResponseMessage = httpClient.PostAsync(
            requestUri,
            jsonContent).get();

        // Make sure the post succeeded, and write out the response.
        httpResponseMessage.EnsureSuccessStatusCode();
        httpResponseBody = httpResponseMessage.Content().ReadAsStringAsync().get();
        std::wcout << httpResponseBody.c_str();
    }
    catch (winrt::hresult_error const& ex)
    {
        std::wcout << ex.message().c_str();
    }
}

Windows.Web.Http içindeki Özel Durumlar

Tek Biçimli Kaynak Tanımlayıcısı (URI) için geçersiz bir dize, Windows.Foundation.Uri nesnesinin oluşturucusuna geçirildiğinde bir özel durum oluşur.

.NET:Windows. Foundation.Uri türü C# ve VB'de System.Uri olarak görünür.

C# ve Visual Basic'de, URI oluşturmadan önce kullanıcıdan alınan dizeyi test etmek için .NET 4.5'teki System.Uri sınıfı ve System.Uri.TryCreate yöntemlerinden biri kullanılarak bu hata önlenebilir.

C++'ta, bir dizeyi URI'ye ayrıştırmaya çalışmak için bir yöntem yoktur. Bir uygulama, Windows.Foundation.Uri için kullanıcıdan girdi alıyorsa, oluşturucu bir try/catch bloğunda yer almalıdır. Bir özel durum oluşursa, uygulama kullanıcıyı bilgilendirebilir ve yeni bir konak adı isteyebilir.

Windows. Web.Http'de kolaylık işlevi yok. Dolayısıyla Bu ad alanında HttpClient ve diğer sınıfları kullanan bir uygulamanın HRESULT değerini kullanması gerekir.

C++/WinRT kullanan uygulamalarda winrt::hresult_error yapısı, uygulama yürütme sırasında ortaya çıkan bir özel durumu temsil eder. winrt::hresult_error::code işlevi, belirli bir özel duruma atanan HRESULT değerini döndürür. winrt::hresult_error::message işlevi, HRESULT değeriyle ilişkili sistem tarafından sağlanan dizeyi döndürür. Daha fazla bilgi için bkz. C++/WinRT ile hata işleme

Olası HRESULT değerleri Winerror.h üst bilgi dosyasında listelenir. Uygulamanız, özel durumun nedenine bağlı olarak uygulama davranışını değiştirmek için belirli HRESULT değerlerini filtreleyebilir.

C#, VB.NET'de .NET Framework 4.5 kullanan uygulamalarda System.Exception, bir özel durum oluştuğunda uygulama yürütme sırasında bir hatayı temsil eder. System.Exception.HResult özelliği, belirli bir özel duruma atanan HRESULT değerini döndürür. System.Exception.Message özelliği, özel durumu açıklayan iletiyi döndürür.

C++/CX yerine C++/WinRT geçti. Ancak C++/CX kullanan uygulamalarda Platform::Exception , bir özel durum oluştuğunda uygulama yürütme sırasında oluşan bir hatayı temsil eder. Platform::Exception::HResult özelliği, belirli bir özel duruma atanan HRESULT değerini döndürür. Platform::Exception::Message özelliği HRESULT değeriyle ilişkili sistem tarafından sağlanan dizeyi döndürür.

Çoğu parametre doğrulama hatasında, döndürülen HRESULT değeri E_INVALIDARG değeridir. Bazı geçersiz yöntem çağrılarında döndürülen HRESULT değeri E_ILLEGAL_METHOD_CALL değeridir.