C# – HTTP 처리하기

http://3.ly/ 는 URL을 줄여주는 서비스를 제공하는데요..
WebMa용 플러그인으로 만들어 본 내용입니다.
http 요청하고 (Get / Post)하고, 결과값으로 받은 html document 에서 newurl 의 값을 추출하는 예제입니다.
(좀 문제가 있어서.. 최종적으로는 javascript를 사용하여 webma용 플러그인으로 만들었습니다. ^^;)

일단 참조추가 하시고 아래 코드를 실행하시면 됩니다.
참조추가 : COM > Microsoft HTML Object Library

// http 호출 (GET)
//string resResult = string.Empty;
//string srcUrl = "http://3.ly/?bm=1&u=" + m_sourceUrl;
//HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(srcUrl);
//HttpWebResponse wRes = (HttpWebResponse)wReq.GetResponse();


// http 호출 (POST)
string resResult = string.Empty;

string postData = "u_id=&u_advanced=&u=" + m_sourceUrl;
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);

HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create("http://3.ly/");
wReq.Method = "POST";
wReq.UserAgent = "Mozilla/4.0";
wReq.ContentType = "application/x-www-form-urlencoded";
wReq.ContentLength = bytes.Length;
wReq.CookieContainer = new CookieContainer();

using (Stream writeStream = wReq.GetRequestStream())
{
    writeStream.Write(bytes, 0, bytes.Length);
}

HttpWebResponse wRes = (HttpWebResponse)wReq.GetResponse();


// http 내용 추출
Stream respPostStream = wRes.GetResponseStream();
StreamReader readerPost = new StreamReader(respPostStream, Encoding.Default);

resResult = readerPost.ReadToEnd();

if (string.IsNullOrEmpty(resResult))
{
    lblResult.Text = "처리하지 못했습니다. [ERR2]";
    return;
}

// Parsing
IHTMLDocument2 doc = (IHTMLDocument2)new HTMLDocument();
doc.clear();
doc.write(resResult);
doc.close();
m_targetUrl = (string)((HTMLDocument)doc).getElementById("newurl").getAttribute("value", 0);

if (string.IsNullOrEmpty(m_targetUrl))
{
    lblResult.Text = "처리하지 못했습니다. [ERR3]";
    return;
}

 

댓글 남기기