iT邦幫忙

DAY 26
3

JSP 學習分享系列 第 26

JSP 應用 抓取網頁內容

預先安裝函式庫:
Apache Commons HttpClient 3.x
Apache Commons Codec
Apache Commons Logging

<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="org.apache.commons.http.client.*" %>
<%@ page import="org.apache.commons.http.client.methods.*" %>
<%@ page import="org.apache.commons.http.client.params.HttpMethodParams" %>
<%@ page import="java.io.*" %>
<%
  String url = "http://tw.stock.yahoo.com/";

  String stockId = request.getParameter("stock_id");
  if (stockId != null) {
    url += "q/q?s=" + stockId;
  }

  // Create an instance of HttpClient.
  HttpClient client = new HttpClient();

  // Create a method instance.
  HttpMethod method = new GetMethod(url);

  // Provide custom retry handler is necessary
  method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
          new DefaultHttpMethodRetryHandler(3, false));

  try {
    // Execute the method.
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
      System.err.println("Method failed: " + method.getStatusLine());
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

    // Deal with the response.
    // Use caution: ensure correct character encoding and is not binary data
    //System.out.println(new String(responseBody));

    String result = new String(responseBody, "Big5");
    if (stockId != null) {
      result = result.substring(result.indexOf("nowrap><b>") + "nowrap><b>".length());
      result = result.substring(0, result.indexOf("</b>"));
      out.println(stockId + " Price Now: " + result);
    } else {
      out.println(result);
    }
  } catch (HttpException e) {
    System.err.println("Fatal protocol violation: " + e.getMessage());
    e.printStackTrace();
  } catch (IOException e) {
    System.err.println("Fatal transport error: " + e.getMessage());
    e.printStackTrace();
  } finally {
    // Release the connection.
    method.releaseConnection();
  }
%>

上一篇
JSP 和 HTTP Header 裡Referer的應用
下一篇
JSP 購物車的範例
系列文
JSP 學習分享30

尚未有邦友留言

立即登入留言