Hunter的大杂烩

May 20, 2007

httpclient & jericho xml范例

Filed under: Java — hunter @ 11:50 pm

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.lang.*;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.HTMLElementName;
import au.id.jericho.lib.html.Segment;
import au.id.jericho.lib.html.Source;

public class HkStockInfo implements StockInfo
{
 private HttpClient httpClient = null;
 public HkStockInfo()
 {
  //构造HttpClient的实例
  httpClient = new HttpClient();
 }


 public Double GetSingleCurrentPrice(int code)
 {
  //String hkcode = String.format(“%04d”, code);
  //创建GET方法的实例
  String url = String.format(“http://www.aastocks.com/chi/stockquote/default.asp?symbol=%04d“, code);
  //System.out.println(“get url:” + url);
  GetMethod getMethod = new GetMethod(url);
  //使用系统提供的默认的恢复策略
  getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
             new DefaultHttpMethodRetryHandler());
  try
  {
   //执行getMethod
   int statusCode = httpClient.executeMethod(getMethod);
   if ( statusCode != HttpStatus.SC_OK )
   {
    //System.out.println(“Method failed: ”
    //       + getMethod.getStatusLine());
    return 0.0;
   }
   //读取内容
   String responseBody = getMethod.getResponseBodyAsString();
            responseBody = new String(responseBody.getBytes(“ISO-8859-1″),”BIG5”);
   //处理内容
   Source source = new Source(responseBody);
            //source.setLogWriter(new OutputStreamWriter(System.err));
   source.fullSequentialParse();
            List fontElements=source.findAllElements(HTMLElementName.FONT);
   for (Iterator i=fontElements.iterator(); i.hasNext();)
   {
    Element fontElement=(Element)i.next();
    String color=fontElement.getAttributeValue(“color”);
    if (color==null || !(color.equals(“green”) || color.equals(“red”)) )
     continue;
    // A element can contain other tags so need to extract the text from it:
    String label=fontElement.getContent().extractText();
    Double ret = new Double(label);
    return ret;
    //System.out.println(color+” (“+label+”)”);
   }
  }
  catch ( HttpException e )
  {
   //发生致命的异常,可能是协议不对或者返回的内容有问题
   System.out.println(“Please check your provided http address!”);
   e.printStackTrace();
  }
  catch ( IOException e )
  {
   //发生网络异常
   e.printStackTrace();
  }
  finally
  {
   //释放连接
   getMethod.releaseConnection();

  }
  System.out.println(“error done “);
  return 0.0;
 }
}

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress