■ POST 요청 데이터를 구하는 방법을 보여준다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Threading.Tasks; #region HTTP 요청하기 (비동기) - HTTPRequestAsync(url, postType, contentType, postData, headerDictionary, token, cookieContainer) /// <summary> /// HTTP 요청하기 (비동기) /// </summary> /// <param name="url">URL</param> /// <param name="postType">POST 타입</param> /// <param name="contentType">컨텐트 타입</param> /// <param name="postData">POST 데이터</param> /// <param name="headerDictionary">헤더 딕셔너리</param> /// <param name="token">토큰</param> /// <param name="cookieContainer">쿠키 컨테이너</param> /// <returns>HTTP 결과 태스크</returns> public async Task<HTTPResult> HTTPRequestAsync ( string url, string postType, string contentType, string postData, IDictionary<string, object> headerDictionary = null, string token = null, CookieContainer cookieContainer = null ) { HttpStatusCode responseCode = HttpStatusCode.OK; string responseData = null; await Task.Run ( () => { HttpWebResponse response = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url)); request.Method = (postType != null) ? postType : "POST"; request.CookieContainer = cookieContainer; request.Credentials = CredentialCache.DefaultCredentials; SetHeader(request, headerDictionary, token); if(postData != null) { byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = (contentType != null) ? contentType : "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(byteArray, 0, byteArray.Length); requestStream.Close(); } response = (HttpWebResponse)request.GetResponse(); } catch(WebException webException) { response = (HttpWebResponse)webException.Response; } catch(Exception exception) { Console.WriteLine($"Exception : {exception.ToString()}"); throw; } if(response != null) { responseCode = ((HttpWebResponse)response).StatusCode; Stream responseStream = response.GetResponseStream(); using(StreamReader reader = new StreamReader(responseStream)) { responseData = reader.ReadToEnd(); } } } ); return new HTTPResult(responseCode, responseData); } #endregion #region 헤더 설정하기 - SetHeader(request, headerDictionary, token) /// <summary> /// 헤더 설정하기 /// </summary> /// <param name="request">HTTP 웹 요청</param> /// <param name="headerDictionary">헤더 딕셔너리</param> /// <param name="token">토큰</param> private void SetHeader(HttpWebRequest request, IDictionary<string, object> headerDictionary, string token) { if(headerDictionary != null) { foreach(KeyValuePair<string, object> keyValuePair in headerDictionary) { string key = keyValuePair.Key; string value = keyValuePair.Value as string; if(key.Equals("Accept", StringComparison.Ordinal)) { request.Accept = value; } else if(key.Equals("KeepAlive", StringComparison.Ordinal)) { request.KeepAlive = bool.Parse(value); } else { request.Headers[key] = value; } } } if(token != null) { request.Headers["Authorization"] = token; } } #endregion /// <summary> /// HTTP 결과 /// </summary> public class HTTPResult { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 결과 코드 /// </summary> public HttpStatusCode StatusCode; /// <summary> /// 메시지 /// </summary> public string Message; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - HTTPResult(statusCode, message) /// <summary> /// 생성자 /// </summary> /// <param name="statusCode">상태 코드</param> /// <param name="message">메시지</param> public HTTPResult(HttpStatusCode statusCode, string message) { StatusCode = statusCode; Message = message; } #endregion } |