조회 수 32602 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print

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");
  
        // 파징 후 각자 활용
    }
}




[예제2]


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
private HtmlAgilityPack.HtmlDocument getpage(string url ,String input)
{
    try
    {
        Stream datastream;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.CookieContainer = new CookieContainer();
        request.CookieContainer.Add(cookies);
        request.AllowAutoRedirect = true;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
        request.ContentType = "application/x-www-form-urlencoded";
 
        if (input!=null)
        {
            String postData = "";
            request.Method = "POST";
            if (input == "login")
            {
                postData = String.Format("username={0}&password={1}", "myusername", "mypassword");
            }
            else if (input == "sendMessage")
            {
            //THIS IS THE LONG STRING THAT I DON'T WANT TO HARD CODE
                postData = String.Format("reciever={0}&sendmessage={1}", "thepersontomessage" ,this.DefaultMessage);
            //I am just puting two parameters for now, there should be alot
            }
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = byteArray.Length;
            datastream = request.GetRequestStream();
            datastream.Write(byteArray, 0, byteArray.Length);
            datastream.Close();
        }
 
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        datastream = response.GetResponseStream();
        String sourceCode = "";
        using (StreamReader reader = new StreamReader(datastream))
        {
            sourceCode = reader.ReadToEnd();
        }
 
        HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
        htmlDoc.LoadHtml(sourceCode);
        this.cookies.Add(response.Cookies);
        return htmlDoc;
    }
    catch (Exception)
    {
        return null;
    }



Dreamy의 코드 스크랩

내가 모으고 내가 보는

List of Articles
번호 분류 제목 날짜 조회 수 추천 수
226 일반 Visul Studio 2013 유용한 단축키 2014.03.01 29491 0
225 PHP MySQL 기본 문법 2014.03.01 15502 0
224 Android Android C, C++ 레벨에서 call stack 보기 file 2014.02.25 22109 0
223 일반 LDAP Query 기본 2014.02.19 30361 0
222 C# DataGridView 컨트롤 Tutorial 2014.02.19 15416 0
» C# HttpWebRequest 로 http GET, POST 전송 및 처리 2014.02.18 32602 0
220 Android 안드로이드 init.rc 문법 2014.02.17 31110 0
219 Android ART(Android RunTime)에 대해 1 2014.02.10 19497 0
218 일반 findstr 사용법 - window용 find, grep 명령 2014.02.04 66756 0
217 Android Android RAM 사용량 측정 2014.02.04 14354 0
216 Android 킷캣에서 바뀐 점 정리 2014.01.26 15535 0
215 LINUX screen 명령어, 터미널 멀티세션 제공 1 2014.01.21 59038 0
214 PHP php 기본 문법 정리 secret 2014.01.16 0 0
213 Android 안드로이드 키 이벤트 (adb shell로 보내는 법) 2014.01.04 52734 0
212 Android adb로 폰 화면 동영상 저장 - KK 전용 2013.12.17 17556 0
목록
Board Pagination ‹ Prev 1 ... 15 16 17 18 19 20 21 22 23 24 ... 35 Next ›
/ 35

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

불러오는 중···