改用
Apache HttpComponents HttpClient 4撰寫的版本:
httpclient4.jsp:
<%@ page contentType="text/html;charset=big5" %>
<%@ page import="java.io.IOException" %>
<%@ page import="org.apache.http.client.ClientProtocolException" %>
<%@ page import="org.apache.http.client.HttpClient" %>
<%@ page import="org.apache.http.client.ResponseHandler" %>
<%@ page import="org.apache.http.client.methods.HttpGet" %>
<%@ page import="org.apache.http.impl.client.BasicResponseHandler" %>
<%@ page import="org.apache.http.impl.client.DefaultHttpClient" %>
<%
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 httpclient = new DefaultHttpClient();
try {
// Create an HttpGet method instance.
HttpGet httpget = new HttpGet(url);
System.out.println("executing request " + httpget.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
if (stockId != null) {
responseBody = responseBody.substring(responseBody.indexOf("nowrap><b>")+"nowrap><b>".length());
responseBody = responseBody.substring(0, responseBody.indexOf("</b>"));
out.println(stockId + " Price Now: " + responseBody);
} else {
out.println(responseBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
%>