EMDI는 지금도 개발중

C# : HttpWebRequest sync 동기식, async 비동기식 본문

언어/C#

C# : HttpWebRequest sync 동기식, async 비동기식

EMDI 2021. 3. 29. 13:09
//------------------------------------------------------------------
// http - sync 동기식
//------------------------------------------------------------------
HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(TargetURi);
httpReq.Method = "POST";
httpReq.ContentType = "application/json;";
using (StreamWriter streamWriter = new StreamWriter(httpReq.GetRequestStream()))
{
    streamWriter.Write(RequestJson);
    streamWriter.Flush();
    streamWriter.Close();
}

httpRes = (HttpWebResponse)httpReq.GetResponse();
Stream RESULT_STREAM = httpRes.GetResponseStream();
//------------------------------------------------------------------
// http - async 비동기식
//------------------------------------------------------------------
httpReq = (HttpWebRequest)HttpWebRequest.Create(TargetURi);
httpReq.Method = "POST";
httpReq.ContentType = "application/json;";

// 비동기식 방법을 사용하게 될 경우 두 번이상의 호출 프로세스를 가질 수 있기 때문에
// 런타임 오류 발생 가능성이 있다. 한 UITread에서 하나의 HttpWebRequest를 허용하기 ㄸ때문에
// 그러므로, request가 종료되기 전에 새로운 request가 발생하지 않도록 로직 주의
httpReq.BeginGetRequestStream(new AsyncCallback((IAsyncResult reqAsyncResult) =>
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)reqAsyncResult.AsyncState;

        // End the operation
        Stream postStream = request.EndGetRequestStream(reqAsyncResult);

        // Convert the string into a byte array.
        byte[] byteArray = Encoding.UTF8.GetBytes(RequestJson);

        // Write to the request stream.
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

    }
    catch (Exception e)
    {
        Trace.WriteLine(e.ToString());
    }

}), httpReq);


httpReq.BeginGetResponse(new AsyncCallback((IAsyncResult resAsyncResult) =>
{
    try
    {
        using (HttpWebResponse response = (HttpWebResponse)httpReq.EndGetResponse(resAsyncResult))
        {
            Stream RESULT_STREAM = response.GetResponseStream();
            response.Close();
        }
    }
    catch (Exception e)
    {
        Trace.WriteLine(e.ToString());
    }

}), httpReq);
Comments