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

▶ HttpWebRequest 클래스 : POST 요청 객체 구하기 예제

using System;

string token;

...

var result = GetPOSTRequestObject<APIModel>
(
    "https://localhost:44362/api/api/inquiryitem",
    token,
    new APIKeyModel { ID = "F835FE23-6AE4-4641-A09B-B9391D90D033" }
);
            
Console.WriteLine(result.NAME);

 

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

 

 

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 요청 객체 구하기 - GetPOSTRequestObject<TObject>(url, token, input)

/// <summary>
/// POST 요청 객체 구하기
/// </summary>
/// <typeparam name="TObject">객체 타입</typeparam>
/// <param name="url">URL</param>
/// <param name="token">토큰</param>
/// <param name="input">입력 객체</param>
/// <returns>POST 요청 객체</returns>
public TObject GetPOSTRequestObject<TObject>(string url, string token, object input)
{
    string resultString = POSTGetString(url, token, "application/json; charset=utf-8", Encoding.UTF8, input);

    TObject result = JsonConvert.DeserializeObject<TObject>(resultString);

    return result;
}

#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
#region POST 문자열 구하기 - POSTGetString(url, token, contentType, encoding, input)

/// <summary>
/// POST 문자열 구하기
/// </summary>
/// <param name="url">URL</param>
/// <param name="token">토큰</param>
/// <param name="contentType">컨텐츠 타입</param>
/// <param name="encoding">인코딩</param>
/// <param name="input">입력 객체</param>
/// <returns>POST 문자열</returns>
private string POSTGetString(string url, string token, string contentType, Encoding encoding, object input)
{
    using Stream stream = GetPOSTRequestStream(url, token, contentType, encoding, input);

    using StreamReader reader = new(stream);

    string result = reader.ReadToEnd();

    return result;
}

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

댓글을 달아 주세요