HttpClient 是 Apache Jakarta Common 下的子項目,能夠用來提供高效的、最新的、
功能豐富的支持 HTTP 協議的客戶端編程工具包,而且它支持 HTTP 協議最新的版本和
建議。
HTTP 協議多是如今 Internet 上使用得最多、最重要的協議了,愈來愈多的 Java
應用程序須要直接經過 HTTP 協議來訪問網絡資源。雖然在 JDK 的 java net 包中已經提
供了訪問 HTTP 協議的基本功能,可是對於大部分應用程序來講, JDK 庫自己提供的功能
還不夠豐富和靈活。
2、 HttpClient 應用
1 發送 GET 請求不帶參數html
添加 HttpClient 座標java
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan ce" xsi:schemaLocation="http://maven.apache.org/P OM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bjsxt</groupId> <artifactId>httpClientDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.http components/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version></dependency> </dependencies> </project>
package com.mikey.HttpClient; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * @Program: HttpClient * @Author: 麥奇 * @Email: 1625017540@qq.com * @Create: 2019-03-30 17:22 * @Describe: **/ public class HttpClientTest { /** * Get 請求不帶參數 * @param args * @throws Exception */ public static void main(String[] args) throws Exception{ //常見一個 HttpClient 對象 CloseableHttpClient aDefault = HttpClients.createDefault(); //建立 Get 請求對象。在請求中輸入 HttpGet httpGet = new HttpGet("http://www.baidu.com"); //發送請求,並返回響應 CloseableHttpResponse execute = aDefault.execute(httpGet); //處理響應 //獲取響應的狀態碼 int code=execute.getStatusLine().getStatusCode(); System.out.println("響應碼:"+code); HttpEntity entity = execute.getEntity(); //獲取響應的內容 String content = EntityUtils.toString(entity, "utf-8"); //打印響應內容 System.out.println("Content:"+content); //關閉鏈接 aDefault.close(); } }
2 發送 GET 請求帶參數mysql
/*** Get 請求帶參數 * @throws Exception */ public static void doGetParam() throws Exception{ CloseableHttpClient client = HttpClients.createDefault(); //建立一個封裝 URI 的對象。在該對象中能夠給定請 求參數 URIBuilder bui = new URIBuilder("https://www.sogou.com/web"); bui.addParameter("query", "西遊記"); //建立一個 Get 請求對象 HttpGet get = new HttpGet(bui.build()); //發送請求,並返回響應 CloseableHttpResponse res = client.execute(get); //處理響應 //獲取響應的狀態碼 int code = res.getStatusLine().getStatusCode();System.out.println(code); //獲取響應的內容 HttpEntity entity = res.getEntity(); String content = EntityUtils.toString(entity,"utf-8"); System.out.println(content); //關閉鏈接 client.close(); }
3 發送 POST 請求不帶參數web
/** * 發送 POST 請求不帶參數 */ public static void doPostTest()throws Exception{ CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost("http://localhost:8080/test/post"); CloseableHttpResponse res =client.execute(post); //處理響應 //獲取響應的狀態碼 int code = res.getStatusLine().getStatusCode(); System.out.println(code); //獲取響應的內容 HttpEntity entity = res.getEntity(); String content = EntityUtils.toString(entity,"utf-8"); System.out.println(content); //關閉鏈接 client.close(); }
4 發送 POST 請求帶參數spring
/** * 發送 POST 請求帶參數 */ public static void doPostParamTest()throws Exception{CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost("http://localhost:8080/test/post/param"); //給定參數 List<BasicNameValuePair> list = new ArrayList<>(); list.add(new BasicNameValuePair("name", "張 三豐")); list.add(new BasicNameValuePair("pwd", "zhangsanfeng")); //將參數作字符串的轉換 StringEntity entity = new UrlEncodedFormEntity(list,"utf-8"); //向請求中綁定參數 post.setEntity(entity); //處理響應 CloseableHttpResponse res = client.execute(post); //獲取響應的狀態碼 int code =res.getStatusLine().getStatusCode(); System.out.println(code); //獲取響應的內容 HttpEntity en = res.getEntity(); String content = EntityUtils.toString(en,"utf-8"); System.out.println(content); //關閉鏈接 client.close(); }
5 在 POST 請求的參數中傳遞 JSON 格式數據sql
/** * 發送 POST 請求帶 JSON 格式參數 */ public static void doPostParamJsonTest()throws Exception{ CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost("http://localhost:8080/test/post/param/js on");String json ="{\"name\":\"張三丰 \",\"pwd\":\"zhangsanfeng\"}"; StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); //向請求中綁定參數 post.setEntity(entity); //處理響應 CloseableHttpResponse res = client.execute(post); //獲取響應的狀態碼 int code = res.getStatusLine().getStatusCode(); System.out.println(code); //獲取響應的內容 HttpEntity en = res.getEntity(); String content = EntityUtils.toString(en,"utf-8"); System.out.println(content); //關閉鏈接 client.close(); }
6 HttpClient 自定義工具類的使用
6.1 編寫工具類apache
public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) { // 建立 Httpclient 對象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 建立 uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); }} URI uri = builder.build(); // 建立 http GET 請求 HttpGet httpGet = new HttpGet(uri); // 執行請求 response = httpclient.execute(httpGet); // 判斷返回狀態是否爲 200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); }httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } public static String doPost(String url, Map<String, String> param) { // 建立 Httpclient 對象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 建立 Http Post 請求 HttpPost httpPost = new HttpPost(url);// 建立參數列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模擬表單 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8"); httpPost.setEntity(entity); } // 執行 http 請求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try {response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } public static String doPost(String url) { return doPost(url, null); } public static String doPostJson(String url, String json) { // 建立 Httpclient 對象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try {// 建立 Http Post 請求 HttpPost httpPost = new HttpPost(url); // 建立請求內容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 執行 http 請求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }return resultString; } }
6.2 測試工具類編程
/** * 測試 HttpClient 工具類 */ public static void httpClientUtilTest(){ String url = "http://localhost:8080/test/post/param"; Map<String, String> param = new HashMap<>(); param.put("name", "李四"); param.put("pwd", "lisi"); String result = HttpClientUtil.doPost(url, param); System.out.println(result); }
1 需求
1) 採用 SOA 架構項目2) 使用 HttpClient 調用服務
3) 完成用戶的添加與查詢
2 項目架構
3 表結構json
CREATE TABLE `users` ( `userid` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(30) DEFAULT NULL, `userage` int(11) DEFAULT NULL, PRIMARY KEY (`userid`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
4 建立項目
4.1 建立 commons 項目
4.1.1 建立項目
4.1.2 需改 POM 文件api
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan ce"xsi:schemaLocation="http://maven.apache.org/P OM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.bjsxt</groupId> <artifactId>parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <groupId>com.bjsxt</groupId> <artifactId>commons</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- Jackson Json 處理工具包 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency><groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version> </dependency> </dependencies> </project>
4.2 建立 service 項目
4.2.1 建立項目4.2.2 修改 POM 文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan ce" xsi:schemaLocation="http://maven.apache.org/P OM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.bjsxt</groupId> <artifactId>parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <groupId>com.bjsxt</groupId> <artifactId>service</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>com.bjsxt</groupId><artifactId>commons</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- 單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <!-- 日誌處理 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId> </dependency> <!-- MySql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 鏈接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency><groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> </resources><!-- tomcat 插件,因爲子項目不必定每一個都是 web 項目,因此該插件只是聲明,並未開啓 --> <plugins> <!-- 配置 Tomcat 插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <configuration> <path>/</path> <port>8080</port> </configuration> </plugin> </plugins> </build> </project>
4.3 建立 client 項目
4.3.1 建立項目
4.3.2 修改 POM 文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan ce" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.bjsxt</groupId> <artifactId>parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <groupId>com.bjsxt</groupId> <artifactId>client</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>com.bjsxt</groupId> <artifactId>commons</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- 單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency><!-- 日誌處理 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <!-- tomcat 插件,因爲子項目不必定每一個都是 web 項目,因此該插件只是聲明,並未開啓 --><plugins> <!-- 配置 Tomcat 插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <configuration> <path>/</path> <port>8081</port> </configuration> </plugin> </plugins> </build> </project>
5 添加用戶
5.1 Client
5.1.1 addUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="/user/addUser" method="post"> 用戶姓名:<input type="text" name="username"/><br/> 用戶年齡:<input type="text" name="userage"/><br/> <input type="submit" value="OKOK"/> </form> </body> </html>
5.1.2 UserService
@Override public void addUser(Users user) { String json = JsonUtils.objectToJson(user); String code = HttpClientUtil.doPostJson("http://localhost:8080/u ser/insertUser", json); Map<String, Integer> map = JsonUtils.jsonToPojo(code, Map.class); Integer var = map.get("code"); if(var == 500){ System.out.println("出錯了"); }else{ System.out.println("添加成功"); } }
5.1.3 UserController
@Controller @RequestMapping("/user") public class UserController {@Autowired private UserService userService; /** * 添加用戶 */ @RequestMapping("/addUser") public String addUser(Users user){ this.userService.addUser(user); return "ok"; } } 5.2 Service 5.2.1 UserController @Controller @RequestMapping("/user") public class UserController { @Autowiredprivate UserService userService; @RequestMapping("/insertUser") @ResponseBody public Object insertUser(@RequestBody Users user){ Map<String, Integer> map = new HashMap<>(); try{ this.userService.insertUser(user); map.put("code", 200); }catch(Exception e){ e.printStackTrace(); map.put("code", 500); } return map; } }
5.2.2 UserService
@Service public class UserServiceImpl implementsUserService { @Autowired private UserMapper userMapper; @Override public void insertUser(Users user) { this.userMapper.insertUser(user); } }
6 查詢用戶
6.1 Client
6.1.1 UserController
/** * 查詢所有用戶 */ @RequestMapping("/findUser") public String findUserAll(Model model){ List<Users> list = this.userService.findUserAll();model.addAttribute("list", list); return "showUser"; } 6.1.2 UserService @Override public List<Users> findUserAll() { String var = HttpClientUtil.doPost("http://localhost:8080/user/ selectUserAll"); List<Users> list = JsonUtils.jsonToList(var, Users.class); return list; }
6.2 Service
6.2.1 UserController
@RequestMapping("/selectUserAll") @ResponseBody public Object selectUserAll(){ return this.userService.selectUserAll(); }6.2.2 UserService @Override public List<Users> selectUserAll() { return this.userMapper.selectUserAll(); }