2010년 11월 29일 월요일

httpclient를 이용한 webpage 긁어오기

public void TestHttpClient ()
{
private StringBuilder sb;
HttpClient httpclient = new DefaultHttpClient();
localContext = new BasicHttpContext();
// Set HttpPost
HttpPost httppost = new HttpPost(LOGIN);

// Set Post Param
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("user_id", ID));
paramList.add(new BasicNameValuePair("password", PW));
httppost.setEntity(new UrlEncodedFormEntity(paramList));
     
// execute Post \ return Response
HttpResponse response = httpclient.execute(httppost, localContext);
// 200 OK ?
if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode())
{
// Set HttpGet

httppost = new HttpPost(BOARD);

paramList = new ArrayList<NameValuePair>();

paramList.add(new BasicNameValuePair("id", BoardID));

paramList.add(new BasicNameValuePair("page", String.valueOf(PageNum)));

if(SearchKey != null)

       {
        if(SN)
            paramList.add(new BasicNameValuePair("sn", "on"));
           else
              paramList.add(new BasicNameValuePair("sn", "off"));
           if(SS)
              paramList.add(new BasicNameValuePair("ss", "on"));
           else
              paramList.add(new BasicNameValuePair("ss", "off"));
           if(SC)
              paramList.add(new BasicNameValuePair("sc", "on"));
           else
            paramList.add(new BasicNameValuePair("sc", "off"));

           String temp = URLEncoder.encode(SearchKey, "euc-kr");
           paramList.add(new BasicNameValuePair("keyword", temp));
}

       httppost.setEntity(new UrlEncodedFormEntity(paramList));
    // execute Get \ return Response
    response = httpclient.execute(httppost, localContext);
   
    // 200 OK?
       if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode())
{

  // Get Context
           InputStream instream = response.getEntity().getContent();
           BufferedReader reader
= new BufferedReader(new InputStreamReader(instream, "euc-kr"));

           String line = null;
           while(null != (line = reader.readLine()))
            {
  sb.append(line);
               sb.append('\n');
           }

            System.out.println(sb);
  }
  }
}


실제 웹페이지 뷰어를 제작할 때 사용한 코드입니다.

paramList.add를 사용, 실제 url에 포함되는 값들을

넣어주면 해당되는 값을 가져오게 됩니다.

또한 한 번 로그인을 하면 localContext 객체 안에 쿠키 정보가 저장되므로

더이상 로그인을 하지 않아도 상관없습니다. (단 사이트마다 다를 수 있음)

자세한 것은 http://hc.apache.org/ 참조. 위 소스코드는 httpclient 3.x 기반

댓글 없음: