첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

▶ HttpWebRequest 클래스 : POST 요청 열거 가능형 구하기 예제

using System;

string token;

...

var resultEnumerable = GetPOSTRequestEnumerable<APIModel>
(
    "https://localhost:44362/api/api/inquirylist",
    token,
    new APISearchConditionModel()
);

int i = 0;

foreach(APIModel api in resultEnumerable)
{
    Console.WriteLine("{0} {1} {2}", i++, api.ID, api.NAME);
}

 

※ APIModel, APISearchConditionModel 타입은 모델 클래스로 명시하지 않았다.

 

 

728x90

 

▶ HttpWebRequest 클래스 : POST 요청 열거 가능형 구하기

using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;

#region POST 요청 열거 가능형 구하기 - GetPOSTRequestEnumerable<TItem>(url, token, input)

/// <summary>
/// POST 요청 열거 가능형 구하기
/// </summary>
/// <typeparam name="TItem">항목 타입</typeparam>
/// <param name="url">URL</param>
/// <param name="token">토큰</param>
/// <param name="input">입력 객체</param>
/// <returns>POST 열거 가능형</returns>
public IEnumerable<TItem> GetPOSTRequestEnumerable<TItem>(string url, string token, object input)
{
    using Stream stream = GetPOSTRequestStream(url, token, "application/json; charset=utf-8", Encoding.UTF8, input);

    using StreamReader streamReader = new(stream);

    using JsonTextReader jsonTextReader = new(streamReader);

    JsonSerializer serializer = new();

    while(jsonTextReader.Read())
    {
        if(jsonTextReader.TokenType != JsonToken.StartArray && jsonTextReader.TokenType != JsonToken.EndArray)
        {
            yield return serializer.Deserialize<TItem>(jsonTextReader);
        }
    }
}

#endregion
#region POST 요청 스트림 구하기 - GetPOSTRequestStream(url, token, contentType, encoding, input, timeOut)

/// <summary>
/// POST 요청 스트림 구하기
/// </summary>
/// <param name="url">URL</param>
/// <param name="token">토큰</param>
/// <param name="contentType">콘텐트 타입</param>
/// <param name="encoding">인코딩</param>
/// <param name="input">입력 객체</param>
/// <param name="timeOut">타임 아웃 (단위 : 밀리초)</param>
/// <returns>POST 요청 스트림</returns>
private Stream GetPOSTRequestStream(string url, string token, string contentType, Encoding encoding, object input, int? timeOut = null)
{
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

    if(!string.IsNullOrWhiteSpace(token))
    {
        request.Headers.Add("Authorization", $"Bearer {token}");
    }

    if(timeOut.HasValue)
    {
        request.Timeout = timeOut.Value;
    }

    if(input != null)
    {
        string inputJSON = JsonConvert.SerializeObject(input);

        byte[] inputByteArray = encoding.GetBytes(inputJSON);

        request.ProtocolVersion           = HttpVersion.Version11;
        request.AllowAutoRedirect         = true;
        request.AllowWriteStreamBuffering = true;
        request.Method                    = WebRequestMethods.Http.Post;
        request.ContentType               = contentType;
        request.ContentLength             = inputByteArray.Length;
        request.PreAuthenticate           = true;

        using(Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(inputByteArray, 0, inputByteArray.Length);
        }
    }
    else
    {
        request.ProtocolVersion           = HttpVersion.Version11;
        request.AllowAutoRedirect         = true;
        request.AllowWriteStreamBuffering = true;
        request.Method                    = WebRequestMethods.Http.Post;
        request.PreAuthenticate           = true;
    }

    HttpWebResponse response = request.GetResponse() as HttpWebResponse;

    Stream responseStream = response.GetResponseStream();

    return responseStream;
}

#endregion
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요