HttpClient

API penting

Gunakan HttpClient dan api namespace Windows.Web.Http lainnya untuk mengirim dan menerima informasi menggunakan protokol HTTP 2.0 dan HTTP 1.1.

Gambaran umum HttpClient dan namespace Windows.Web.Http

Kelas di namespace Windows.Web.Http dan namespace Windows.Web.Http.Headers dan Windows.Web.Http.Filters menyediakan antarmuka pemrograman untuk aplikasi Platform Windows Universal (UWP) yang bertindak sebagai klien HTTP untuk melakukan permintaan GET dasar atau menerapkan fungsionalitas HTTP yang lebih canggih yang tercantum di bawah ini.

  • Metode untuk kata kerja umum (DELETE, GET, PUT, dan POST). Masing-masing permintaan ini dikirim sebagai operasi asinkron.

  • Dukungan untuk pengaturan dan pola autentikasi umum.

  • Akses ke detail Secure Sockets Layer (SSL) pada transportasi.

  • Kemampuan untuk menyertakan filter yang disesuaikan dalam aplikasi tingkat lanjut.

  • Kemampuan untuk mendapatkan, mengatur, dan menghapus cookie.

  • Info kemajuan Permintaan HTTP tersedia pada metode asinkron.

Kelas Windows.Web.Http.HttpRequestMessage mewakili pesan permintaan HTTP yang dikirim oleh Windows.Web.Http.Http.HttpClient. Kelas Windows.Web.Http.HttpResponseMessage mewakili pesan respons HTTP yang diterima dari permintaan HTTP. Pesan HTTP didefinisikan dalam RFC 2616 oleh IETF.

Namespace Layanan Windows.Web.Http mewakili konten HTTP sebagai isi dan header entitas HTTP termasuk cookie. Konten HTTP dapat dikaitkan dengan permintaan HTTP atau respons HTTP. Namespace Windows.Web.Http menyediakan sejumlah kelas berbeda untuk mewakili konten HTTP.

Cuplikan kode di bagian "Kirim permintaan GET sederhana melalui HTTP" menggunakan kelas HttpStringContent untuk mewakili respons HTTP dari permintaan HTTP GET sebagai string.

Namespace Layanan Windows.Web.Http.Headers mendukung pembuatan header HTTP dan cookie, yang kemudian dikaitkan sebagai properti dengan objek HttpRequestMessage dan HttpResponseMessage.

Mengirim permintaan GET sederhana melalui HTTP

Seperti disebutkan sebelumnya dalam artikel ini, namespace Windows.Web.Http memungkinkan aplikasi UWP untuk mengirim permintaan GET. Cuplikan kode berikut menunjukkan cara mengirim permintaan GET menggunakan http://www.contoso.comkelas Windows.Web.Http.HttpClient dan kelas Windows.Web.Http.Http.HttpResponseMessage untuk membaca respons dari permintaan GET.

//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 = "ie";
if (!headers.UserAgent.TryParseAdd(header))
{
    throw new Exception("Invalid header value: " + header);
}

header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
if (!headers.UserAgent.TryParseAdd(header))
{
    throw new Exception("Invalid header value: " + header);
}

Uri requestUri = new Uri("http://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"ie" };
    if (!headers.UserAgent().TryParseAdd(header))
    {
        throw L"Invalid header value: " + header;
    }

    header = L"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
    if (!headers.UserAgent().TryParseAdd(header))
    {
        throw L"Invalid header value: " + header;
    }

    Uri requestUri{ L"http://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;
}

POST data biner melalui HTTP

Contoh kode C++/WinRT di bawah ini menggambarkan menggunakan data formulir dan permintaan POST untuk mengirim sejumlah kecil data biner sebagai unggahan file ke server web. Kode menggunakan kelas HttpBufferContent untuk mewakili data biner, dan kelas HttpMultipartFormDataContent untuk mewakili data formulir multi-bagian.

Catatan

Memanggil get (seperti yang terlihat dalam contoh kode di bawah) tidak sesuai untuk utas UI. Untuk teknik yang benar untuk digunakan dalam hal ini, lihat Operasi konkurensi dan asinkron dengan C++/WinRT.

// 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;
}

Untuk MEMPOSTING konten file biner aktual (daripada data biner eksplisit yang digunakan di atas), Anda akan merasa lebih mudah untuk menggunakan objek HttpStreamContent . Buat satu dan, sebagai argumen ke konstruktornya, teruskan nilai yang dikembalikan dari panggilan ke StorageFile.OpenReadAsync. Metode tersebut mengembalikan aliran untuk data di dalam file biner Anda.

Selain itu, jika Anda mengunggah file besar (lebih besar dari sekitar 10MB), kami sarankan Anda menggunakan WINDOWS Runtime Background Transfer API.

DATA POST JSON melalui HTTP

Contoh berikut memposting beberapa JSON ke titik akhir, lalu menulis isi respons.

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();
    }
}

Pengecualian di Windows.Web.Http

Pengecualian dilemparkan ketika string yang tidak valid untuk Pengidentifikasi Sumber Daya Seragam (URI) diteruskan ke konstruktor untuk objek Windows.Foundation.Uri.

.NET: Jenis Windows.Foundation.Uri muncul sebagai System.Uri di C# dan VB.

Di C# dan Visual Basic, kesalahan ini dapat dihindari dengan menggunakan kelas System.Uri di .NET 4.5 dan salah satu metode System.Uri.TryCreate untuk menguji string yang diterima dari pengguna sebelum URI dibangun.

Di C++, tidak ada metode untuk mencoba dan mengurai string ke URI. Jika aplikasi mendapatkan input dari pengguna untuk Windows.Foundation.Uri, konstruktor harus berada di blok coba/tangkap. Jika pengecualian dilemparkan, aplikasi dapat memberi tahu pengguna dan meminta nama host baru.

Windows.Web.Http tidak memiliki fungsi kenyamanan. Jadi aplikasi yang menggunakan HttpClient dan kelas lain di namespace layanan ini perlu menggunakan nilai HRESULT .

Dalam aplikasi yang menggunakan C++/WinRT, struktur winrt::hresult_error mewakili pengecualian yang dimunculkan selama eksekusi aplikasi. Fungsi winrt::hresult_error::code mengembalikan HRESULT yang ditetapkan ke pengecualian tertentu. Fungsi winrt::hresult_error::message mengembalikan string yang disediakan sistem yang terkait dengan nilai HRESULT . Untuk informasi selengkapnya, lihat Penanganan kesalahan dengan C++/WinRT

Nilai HRESULT yang mungkin tercantum dalam file header Winerror.h. Aplikasi Anda dapat memfilter nilai HRESULT tertentu untuk memodifikasi perilaku aplikasi tergantung pada penyebab pengecualian.

Dalam aplikasi yang menggunakan .NET Framework 4.5 di C#, VB.NET, System.Exception mewakili kesalahan selama eksekusi aplikasi saat pengecualian terjadi. Properti System.Exception.HResult mengembalikan HRESULT yang ditetapkan ke pengecualian tertentu. Properti System.Exception.Message mengembalikan pesan yang menjelaskan pengecualian.

C++/CX telah digantikan oleh C++/WinRT. Tetapi dalam aplikasi yang menggunakan C++/CX, Platform::Exception mewakili kesalahan selama eksekusi aplikasi saat pengecualian terjadi. Properti Platform::Exception::HResult mengembalikan HRESULT yang ditetapkan ke pengecualian tertentu. Properti Platform::Exception::Message mengembalikan string yang disediakan sistem yang terkait dengan nilai HRESULT .

Untuk sebagian besar kesalahan validasi parameter, HRESULT yang dikembalikan E_INVALIDARG. Untuk beberapa panggilan metode ilegal, HRESULT yang dikembalikan E_ILLEGAL_METHOD_CALL.