조회 수 28716 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print

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

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

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

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




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 인코딩
        }
 
        string url = "http://portal.unist.ac.kr/EP/web/collaboration/bbs/jsp/BB_BoardLst.jsp?boardid="
            + 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]


    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
번호 분류 제목 날짜 조회 수 추천 수
281 C# Download Files from Web [C#] 2014.09.11 9003 0
280 Android Android Studio 안드로이드 스튜디오 단축키 2020.03.16 3480 0
279 Android JNI에서 가변 인수(varargs) 쓰기 2014.08.04 7513 0
278 C++ Cast. 캐스팅. 형변환 2014.08.04 9526 0
277 Android adb monkey script 2014.07.30 14634 0
276 Android adb shell monkey - Monkey 사용하기 2014.07.30 27117 0
275 Android adb 를 이용한 터치 이벤트 보내기 2014.07.30 9235 0
274 Android Android Framework 분석을 위한 C++ 강의노트 secret 2014.07.25 0 0
273 LINUX CR, LF, ^M - vi로 DOS<->UNIX 줄바꿈 전환 2014.07.14 37542 0
272 PHP Simple GD example 2014.07.10 7742 0
271 PHP GD 및 이미지 함수 정리 2014.07.09 12684 0
270 PHP PHP GD 설명 2014.07.09 10039 0
269 PHP GD 라이브러리 간단 2014.07.09 9300 0
268 Python 커맨드 라인에서 컬러로 출력하기 termcolor 2014.06.27 10597 0
267 LINUX 우분투 root 계정 사용하기 2014.06.18 8134 0
목록
Board Pagination ‹ Prev 1 ... 11 12 13 14 15 16 17 18 19 20 ... 34 Next ›
/ 34

나눔글꼴 설치 안내


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

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

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5