今天在項目中看到HttpClient的內容,然后去看了一下資料,有了初步的見解,在此記錄一下~
一. 搭建環境
(1)創建一個java項目叫HttpClientTest
(2)為了使用HttpClient的類,你需要導入一下jar包:

(3)創建一個類,名叫Test1
二.HttpClient模擬http請求
Test1代碼如下:
package com.vmaxtam;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpMethod;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;public class Test1 { public static void main(String[] args) throws Exception { //用于模擬客戶端發送請求和接收響應 HttpClient client = new HttpClient(); // 使用 GET 方法 ,如果服務器需要通過 HTTPS 連接,那只需要將下面 URL 中的 http 換成 https HttpMethod method = new GetMethod("http://java.sun.com"); // 使用POST方法 //HttpMethod method = new PostMethod("http://java.sun.com"); //發送請求 client.executeMethod(method); // 打印服務器返回的狀態行 System.out.PRintln(method.getStatusLine()); System.out.println("-------------------------1"); // 返回的信息 System.out.println(method.getResponseBodyAsString()); // 釋放連接 method.releaseConnection(); }}運行main方法后,你會發現,method里頭封裝了sun頁面的html代碼。。。。。
三. 連接自己的服務端
為了證明 二 中的觀點,我們寫一個自己的服務端,還有頁面。
(1)建立一個項目作為服務端,新建一個web項目,名字叫MyServer
(2)WEB-INF 里頭自動生成了 index.jsp
(3)把MyServer部署在開發環境的服務器上,運行起來。
(4)在剛才Test1的main方法中,修改聲明method變量時作為構造方法參數字符串 :
HttpMethod method = new GetMethod("http://localhost:8080/MyServer/index.jsp");(5)運行Test1中的main方法,你會發現,method.getResponseBodyAsString()返回的的確就是index.jsp的代碼
四.連接到servlet,并返回特定的字符串
(1)在剛才的MyServer項目中,新建一個Servlet,名叫Myservlet
(2)編輯Myservlet,代碼如下
package servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class Myservlet */public class Myservlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("you are crazy!"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("Game Over!"); }}(3)別忘了在web.xml中配置這個servlet
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <description> </description> <display-name>Myservlet</display-name> <servlet-name>Myservlet</servlet-name> <servlet-class>servlet.Myservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Myservlet</servlet-name> <url-pattern>/Myservlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
(4)在剛才Test1的main方法中,修改聲明method變量時作為構造方法參數字符串 :
HttpMethod method = new GetMethod("http://localhost:8080/SSH/Myservlet");(5)運行Test1的main方法,你會發現,我們能夠跨項目獲得字符串內容了~
新聞熱點
疑難解答