URI (별칭식 경로 : Uniform Resource Identifier 통합 자원 식별자)
URI는 특정 리소스를 식별하는 경로를 의미한다. 웹 기술에서 사용하는 논리적 또는 물리적 리소스를 식별하는 고유한 문자열 시퀀스다.

URL (절대 경로 : Uniform Resource Locator 또는 통칭 web address)
URL은 흔히 웹 주소라고도 하며, 컴퓨터 네트워크 상에서 리소스가 어디 있는지 알려주기 위한 규약이다. URI의 서브셋이다.

 

GET 방식은 헤더 부분인 주소(URI)에 변수와 값 을 통해 결과를 얻어오는 방법 입니다.

주소 뒷 쪽에 ? 변수1 = 값1 & 변수2 = 값2

 

식으로 변수와 값을 넘겨줄 수 있습니다. 아래는 구글에 간단하게 hi 를 GET으로 요청한 결과 입니다.

https://google.com/search 에 대해해 뒷 편에 ? q = hi 를 붙인 것이죠.

                                                                    (q는 검색어 변수, hi는 값이 되겠죠)

구글에서 hi 검색한 결과

C#에서 호출 한 소스는 아래와 같습니다.

통신을 위해서 json 을 반환시키기도 하며 200(응답 성공), 400(클라이언트 에러), 500(서버쪽 에러) 를 통해

결과를 알 수도 있습니다.

 

.NET 에 따라 SecurityProtocol 값이 달라질 수 있습니다. (현재 .NET 4.7.2 로 작성 되었습니다.)

(ServicePointManager 첫 연결 시만 등록해주면 됩니다.)

using System;
using System.IO;  //Stream
using System.Net; //HttpWebRequest, WebRequest 등 사용
using System.Windows.Forms;

using System.Net.Security; //SSL (Secure Sockets Layer) 관련
using System.Security.Cryptography.X509Certificates; //암호화 된 인증서 관련

namespace WindowsFormsApp10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button_request_Click(object sender, EventArgs e)
        {
            //****************************** 이 부분은 첫 사용하기 전에만 넣어주면 됩니다. ***********************************
            //웹 통신 시 System.Net.WebException : 기본 연결이 닫혔습니다. 관련 에러 방지용 프로토콜 정의입니다.
            //Secure Sockets Layer, Transport Layer Secure
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
                                                   SecurityProtocolType.Tls11 |
                                                   SecurityProtocolType.Tls12 |
                                                   SecurityProtocolType.Ssl3;

            //https (hyper text transfer protocol Secure : 전송 규약 보안) 보안이 올바른지 확인하는 구문입니다. 
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
            //****************************************************************************************************************

            string uri = textBox_uri.Text;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);   //요청 준비
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse(); //요청 후 결과 반환

                Stream stream = response.GetResponseStream();   //요청에 대한 stream 가져오기
                StreamReader reader = new StreamReader(stream); //해당 stream 읽기 위한 streamReader

                string result = reader.ReadToEnd(); //결과 읽어오기

                reader.Close();
                stream.Close();

                textBox_result.Text = result;
            }
            catch (Exception ex)
            {
                textBox_result.Text = "Request Error" + Environment.NewLine + ex.ToString();
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }

        private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            //인증서에 대한 결과를 보려면 여기서 브레이크 걸고 certificate, chain 등을 살펴보면 됩니다.
            //권장하지 않는 방법이지만 인증 기관에 대해 true로 설정해둡니다.
            return true;
        }
    }
}

 

+ Recent posts