Microsoft MVP성태의 닷넷 이야기
.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [링크 복사], [링크+제목 복사]
조회: 11986
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 3개 있습니다.)
.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계
; https://www.sysnet.pe.kr/2/0/12023

.NET Framework: 861. HttpClient와 HttpClientHandler의 관계
; https://www.sysnet.pe.kr/2/0/12024

닷넷: 2200.  C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
; https://www.sysnet.pe.kr/2/0/13522




HttpClient와 HttpClientHandler의 관계

지난 글에 다룬 내용을,

ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계
; https://www.sysnet.pe.kr/2/0/12023

좀 더 심화해서 들어가 보겠습니다. ^^ 이를 위해서는 HttpClient와 HttpClientHandler의 관계를 알아야 합니다. 사실 HttpClient는 HTTP를 위한 GET/PUT/POST 등의 비동기 호출을 감싸는 래퍼 클래스에 불과하고 실질적인 소켓 관리는 HttpClientHandler가 합니다.

HttpClient의 생성자 중 다음과 같은 유형으로 호출하면,

HttpClient clnt1 = new HttpClient(); // 전달된 HttpClientHandler가 없으므로 내부에서 새롭게 하나 생성
HttpClient clnt2 = new HttpClient(new HttpClientHandler());

그 스스로가 Dispose될 때 HttpClientHandler 인스턴스도 함께 Dispose시킵니다. 만약 그것을 원치 않는다면 다른 생성자를 이용해 Handler의 dispose 여부를 결정하는 인자를 넘기면 됩니다.

HttpClient clnt3 = new HttpClient(new HttpClientHandler(), false);

따라서 지난 글에서 HttpClient를 static 전역 객체로 하나만 정의해서 사용하라고 했는데, 엄밀히는 HttpClientHandler를 static으로 정의해 개별 HttpClient에서 사용하는 식으로 바꿔도 무방합니다.

static HttpClientHandler _sharedHandler = new HttpClientHandler();

void Call()
{
    using (HttpClient clnt = new HttpClient(_sharedHandler, false))
    {
        // clnt 사용한 HTTP 호출
    }
}




좀 더 아래로 내려가 보면, HttpClient와 HttpClientHandler의 부모 클래스는 다음과 같습니다.

HttpClient : HttpMessageInvoker
HttpClientHandler : abstract HttpMessageHandler

HttpClient의 역할이 단순한 래퍼라고 했는데, handler를 이용한 기본적인 호출 코드는 부모인 HttpMessageInvoker 클래스가 이미 구현하고 있습니다. 따라서, HttpClient가 아닌 HttpMessageInvoker를 직접 사용하는 것도 가능합니다.

static HttpClientHandler _sharedHandler = new HttpClientHandler { MaxConnectionsPerServer = 3 };

private static async Task requestHttpAsync(object state)
{
    using (HttpMessageInvoker httpClient = new HttpMessageInvoker(_sharedHandler, false))
    {
        try
        {
            HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, url);
            HttpResponseMessage resp = await httpClient.SendAsync(req, CancellationToken.None);
            string result = await resp.Content.ReadAsStringAsync();
        }
        catch { }
    }
}

이 정도면, 대충 웬만큼은 파악이 된 거 같군요. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 9/20/2019]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2020-12-11 03시29분
You're using HttpClient wrong and it is destabilizing your software
; https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
정성태
2022-09-05 11시43분
[양주멋쟁이] 고민되는 내용인데 이거로 정리가 되네요
[guest]

... 16  17  18  19  20  21  22  23  24  [25]  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13005정성태3/17/20226197오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
13004정성태3/16/20226203디버깅 기술: 182. windbg - 닷넷 메모리 덤프에서 AppDomain에 걸친 정적(static) 필드 값을 조사하는 방법
13003정성태3/15/20226352.NET Framework: 1179. C# - (.NET Framework를 위한) Oracle.ManagedDataAccess 패키지의 성능 카운터 설정 방법
13002정성태3/14/20227125.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
13001정성태3/13/20227489.NET Framework: 1177. C# - 닷넷에서 허용하는 메서드의 매개변수와 호출 인자의 최대 수
13000정성태3/12/20227074.NET Framework: 1176. C# - Oracle.ManagedDataAccess.Core의 성능 카운터 설정 방법
12999정성태3/10/20226590.NET Framework: 1175. Visual Studio - 프로젝트 또는 솔루션의 Clean 작업 시 응용 프로그램에서 생성한 파일을 함께 삭제파일 다운로드1
12998정성태3/10/20226168.NET Framework: 1174. C# - ELEMENT_TYPE_FNPTR 유형의 사용 예
12997정성태3/10/202210590오류 유형: 799. Oracle.ManagedDataAccess - "ORA-01882: timezone region not found" 오류가 발생하는 이유
12996정성태3/9/202215712VS.NET IDE: 175. Visual Studio - 인텔리센스에서 오버로드 메서드를 키보드로 선택하는 방법
12995정성태3/8/20228019.NET Framework: 1173. .NET에서 Producer/Consumer를 구현한 BlockingCollection<T>
12994정성태3/8/20227293오류 유형: 798. WinDbg - Failed to load data access module, 0x80004002
12993정성태3/4/20227126.NET Framework: 1172. .NET에서 Producer/Consumer를 구현하는 기초 인터페이스 - IProducerConsumerCollection<T>
12992정성태3/3/20228553.NET Framework: 1171. C# - BouncyCastle을 사용한 암호화/복호화 예제파일 다운로드1
12991정성태3/2/20227716.NET Framework: 1170. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcode_aac.c 예제 포팅
12990정성태3/2/20227316오류 유형: 797. msbuild - The BaseOutputPath/OutputPath property is not set for project '[...].vcxproj'
12989정성태3/2/20226846오류 유형: 796. mstest.exe - System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.Tips.WebLoadTest.Tip
12988정성태3/2/20225805오류 유형: 795. CI 환경에서 Docker build 시 csproj의 Link 파일에 대한 빌드 오류
12987정성태3/1/20227300.NET Framework: 1169. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 demuxing_decoding.c 예제 포팅
12986정성태2/28/20228144.NET Framework: 1168. C# -IIncrementalGenerator를 적용한 Version 2 Source Generator 실습 [1]
12985정성태2/28/20228068.NET Framework: 1167. C# -Version 1 Source Generator 실습
12984정성태2/24/20227144.NET Framework: 1166. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 filtering_video.c 예제 포팅
12983정성태2/24/20227234.NET Framework: 1165. .NET Core/5+ 빌드 시 runtimeconfig.json에 설정을 반영하는 방법
12982정성태2/24/20227157.NET Framework: 1164. HTTP Error 500.31 - ANCM Failed to Find Native Dependencies
12981정성태2/23/20226750VC++: 154. C/C++ 언어의 문자열 Literal에 인덱스 적용하는 구문 [1]
12980정성태2/23/20227523.NET Framework: 1163. C# - 윈도우 환경에서 usleep을 호출하는 방법 [2]
... 16  17  18  19  20  21  22  23  24  [25]  26  27  28  29  30  ...