반응형
Windows.Web.Http.HttpClient 클래스를 사용한 PATCH 비동기 요청
수업에 PATCH
요청 을해야하는데 Windows.Web.Http.HttpClient
어떻게해야하는지에 대한 공식 문서가 없습니다. 어떻게 할 수 있습니까?
여기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;
}
업데이트 : 더 나은 솔루션은 아래 SSX-SL33PY의 답변을 참조하십시오 .
확장 메서드와 동일한 메서드를 작성할 수 있으므로 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);
@ alexander-pacha의 답변을 확장하고 공통 라이브러리 어딘가에 다음 확장 클래스를 추가하는 것이 좋습니다. 이것이 프로젝트 / 클라이언트 / 프레임 워크 / ...에 대한 공통 라이브러리인지 여부는 스스로 만들어야합니다.
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
처리하도록 설계된 모든 것을 처리 할 수 있습니다.
작동하려면 다음과 같은 내용을 전달해야합니다.
HttpContent httpContent = new StringContent("Your JSON-String", Encoding.UTF8, "application/json-patch+json");
반응형
'developer tip' 카테고리의 다른 글
배포 인증서에 개인 키를 추가하려면 어떻게해야합니까? (0) | 2020.12.03 |
---|---|
그리드 간격 변경 및 Matplotlib에서 눈금 레이블 지정 (0) | 2020.12.03 |
Realm 모델의 속성으로 열거 형 사용 (0) | 2020.12.03 |
React Native의 setTimeout (0) | 2020.12.03 |
템플릿 제약 C ++ (0) | 2020.12.03 |