彰化一整天的論壇

 找回密碼
 立即註冊
查看: 840|回復: 0

JSP 應用 抓取網頁內容

[複製鏈接]
發表於 2015-6-3 14:26:11 | 顯示全部樓層 |閱讀模式
  1. <%@ page contentType="text/html" pageEncoding="UTF-8"%>
  2. <%@ page import="org.apache.commons.http.client.*" %>
  3. <%@ page import="org.apache.commons.http.client.methods.*" %>
  4. <%@ page import="org.apache.commons.http.client.params.HttpMethodParams" %>
  5. <%@ page import="java.io.*" %>
  6. <%
  7.   String url = "http://tw.stock.yahoo.com/";

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

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

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

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

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

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

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

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

  30.     String result = new String(responseBody, "Big5");
  31.     if (stockId != null) {
  32.       result = result.substring(result.indexOf("nowrap><b>") + "nowrap><b>".length());
  33.       result = result.substring(0, result.indexOf("</b>"));
  34.       out.println(stockId + " Price Now: " + result);
  35.     } else {
  36.       out.println(result);
  37.     }
  38.   } catch (HttpException e) {
  39.     System.err.println("Fatal protocol violation: " + e.getMessage());
  40.     e.printStackTrace();
  41.   } catch (IOException e) {
  42.     System.err.println("Fatal transport error: " + e.getMessage());
  43.     e.printStackTrace();
  44.   } finally {
  45.     // Release the connection.
  46.     method.releaseConnection();
  47.   }
  48. %>
複製代碼
資料來源:  http://ithelp.ithome.com.tw/question/10033897
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

 ㄚ母滴雞湯
 員林香純滴雞精

Archiver|手機版|小黑屋|彰化一整天的論壇(Excel,Office)  |网站地图

GMT+8, 2019-8-23 22:16 , Processed in 0.151848 second(s), 19 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表