본문 바로가기

프로그램&DB/C#

[C#] HttpWebRequest 로 http GET, POST 전송 및 처리 by carpedm20님

[C#] HttpWebRequest 로 http GET, POST 전송 및 처리



C# 에서 GET 혹은 POST 방식으로 http 리퀘스트를 보내는 예제입니다.

HttpWebRequest 인스턴스의 CookieContainer 를 이용하면 쿠키도 설정할 수 있습니다.

한글 값을 POST 방식으로 전송할 경우 UTF8 인코딩을 해서

바이트 데이터로 바꾼 후 HttpWebRequest 에 추가해 주시면 됩니다.

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
HttpWebRequest wReq;
HttpWebResponse wRes;
 
private bool getResponse(String url, string cookie, string data)
{
    string cookie;
 
    try
    {
        uri = new Uri(url); // string 을 Uri 로 형변환
        wReq = (HttpWebRequest)WebRequest.Create(uri); // WebRequest 객체 형성 및 HttpWebRequest 로 형변환
        wReq.Method = "GET"; // 전송 방법 "GET" or "POST"
        wReq.ServicePoint.Expect100Continue = false;
        wReq.CookieContainer = new CookieContainer();
        wReq.CookieContainer.SetCookies(uri, cookie); // 넘겨줄 쿠키가 있을때 CookiContainer 에 저장
 
        /* POST 전송일 경우
        byte[] byteArray = Encoding.UTF8.GetBytes(data);
 
        Stream dataStream = wReq.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        */
 
        using (wRes = (HttpWebResponse)wReq.GetResponse())
        {
            Stream respPostStream = wRes.GetResponseStream();
            StreamReader readerPost = new StreamReader(respPostStream,  Encoding.GetEncoding("EUC-KR"), true);
 
            resResult = readerPost.ReadToEnd();
        }
 
        return true;
    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
        {
            var resp = (HttpWebResponse)ex.Response;
            if (resp.StatusCode == HttpStatusCode.NotFound)
            {
                // 예외 처리
            }
            else
            {
                // 예외 처리
            }
        }
        else
        {
            // 예외 처리
        }
 
        return false;
    }
}
 
 
// 활용 예제
private void searchBoard(PortalBoard[] board, string boardId, int sPage, int ePage, string query)
{
    MainForm.gridView.Columns[4].HeaderText = "조회수";
 
    for (int i = 0; i < 10 * 10; i++)
    {
        board[i] = new PortalBoard();
    }
 
    for (int pageNum = sPage; pageNum <= ePage; pageNum++)
    {
        byte[] b = System.Text.Encoding.GetEncoding(51949).GetBytes(query);
        string result = "";
 
        foreach (byte ch in b)
        {
            result += ("%" + string.Format("{0:x2} ", ch)); // EUC-KR 인코딩
        }
 
            + boardId + "&nfirst=" + pageNum
            + "&searchcondition=BULLTITLE&searchname=" + result.Replace(" ","");
 
        if (!getResponse(url)) // HttpWebRequest 전송
            return;
 
        doc = (IHTMLDocument2)new HTMLDocument(); // 파징을 위해 IHTMLDocument2 객체 생성
        // IHTMLDocument1, IHTMLDocument2, IHTMLDocument3, IHTMLDocument4
        // 데이터형 마다 사용할 수 있는 함수 종류 다름. msdn 참고
 
        doc.clear();
        doc.write(resResult);
        doc.close();
 
        IEnumerable<ihtmlelement> titles = ElementsByClass(doc, "ltb_left");   
        IEnumerable<ihtmlelement> elements = ElementsByClass(doc, "ltb_center");
 
        // 파징 후 각자 활용
    }
}</ihtmlelement></ihtmlelement>


[출처] carpedm20님 블로그 http://carpedm20.blogspot.kr/2013/04/c-httpwebrequest-http.html