Мне нужно сделать запрос PATCH
с классом Windows.Web.Http.HttpClient
, и нет официальной документации о том, как это сделать. Как я могу это сделать?
PATCH Асинхронные запросы с классом Windows.Web.Http.HttpClient
Ответ 1
Я нашел, как сделать "пользовательский" PATCH
запрос с предыдущим System.Net.Http.HttpClient
классом здесь, а затем поиграть до тех пор, пока я заставил его работать в классе Windows.Web.Http.HttpClient
, например:
public async Task<HttpResponseMessage> PatchAsync(HttpClient client, Uri requestUri, IHttpContent iContent) {
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUri) {
Content = iContent
};
HttpResponseMessage response = new HttpResponseMessage();
// In case you want to set a timeout
//CancellationToken cancellationToken = new CancellationTokenSource(60).Token;
try {
response = await client.SendRequestAsync(request);
// If you want to use the timeout you set
//response = await client.SendRequestAsync(request).AsTask(cancellationToken);
} catch(TaskCanceledException e) {
Debug.WriteLine("ERROR: " + e.ToString());
}
return response;
}
Ответ 2
Вы можете написать тот же самый метод, что и метод расширения, поэтому вы можете вызвать его непосредственно на объекте HttpClient:
public static class HttpClientExtensions
{
public static async Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent iContent)
{
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUri)
{
Content = iContent
};
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.SendAsync(request);
}
catch (TaskCanceledException e)
{
Debug.WriteLine("ERROR: " + e.ToString());
}
return response;
}
}
Использование:
var responseMessage = await httpClient.PatchAsync(new Uri("testUri"), httpContent);
Ответ 3
Я хотел бы расширить ответ на @alexander-pacha и предложить добавить следующий класс расширения где-нибудь в общей библиотеке. Wether это будет общей библиотекой для проекта/клиента/рамки/... это то, что вам придется разобрать самостоятельно.
public static class HttpClientExtensions
{
/// <summary>
/// Send a PATCH request to the specified Uri as an asynchronous operation.
/// </summary>
///
/// <returns>
/// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation.
/// </returns>
/// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception>
public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content)
{
return client.PatchAsync(CreateUri(requestUri), content);
}
/// <summary>
/// Send a PATCH request to the specified Uri as an asynchronous operation.
/// </summary>
///
/// <returns>
/// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation.
/// </returns>
/// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception>
public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent content)
{
return client.PatchAsync(requestUri, content, CancellationToken.None);
}
/// <summary>
/// Send a PATCH request with a cancellation token as an asynchronous operation.
/// </summary>
///
/// <returns>
/// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation.
/// </returns>
/// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception>
public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content, CancellationToken cancellationToken)
{
return client.PatchAsync(CreateUri(requestUri), content, cancellationToken);
}
/// <summary>
/// Send a PATCH request with a cancellation token as an asynchronous operation.
/// </summary>
///
/// <returns>
/// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation.
/// </returns>
/// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception>
public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent content, CancellationToken cancellationToken)
{
return client.SendAsync(new HttpRequestMessage(new HttpMethod("PATCH"), requestUri)
{
Content = content
}, cancellationToken);
}
private static Uri CreateUri(string uri)
{
return string.IsNullOrEmpty(uri) ? null : new Uri(uri, UriKind.RelativeOrAbsolute);
}
}
Таким образом, вы не ожидаете и не выполняете выполнение в каком-то статическом классе расширения, но вы справляетесь с этим, как будто вы действительно делаете вызов PostAsync или PutAsync. У вас также есть те же самые перегрузки в вашем распоряжении, и вы позволяете HttpClient обрабатывать все, что было разработано для обработки.
Ответ 4
Для этого вам необходимо передать содержимое следующим образом:
HttpContent httpContent = new StringContent ( "Ваша JSON-String", Encoding.UTF8, "application/json-patch + json" );