1、課程介紹
2、今日內容簡單介紹
3、Httpclient介紹與實戰
4、項目源碼與資料下載
5、參考文章javascript
一共14天課程
(1)第一天:電商行業的背景。淘淘商城的介紹。搭建項目工程。Svn的使用。
(2)次日:框架的整合。後臺管理商品列表的實現。分頁插件。
(3)第三天:後臺管理。商品添加。商品類目的選擇、圖片上傳、富文本編輯器的使用。
(4)第四天:商品規格的實現。
(5)第五天:商城前臺系統的搭建。首頁商品分類的展現。Jsonp。
(6)第六天:cms系統的實現。前臺大廣告位的展現。
(7)第七天:cms系統添加緩存。Redis。緩存同步。
(8)第八天:搜索功能的實現。使用solr實現搜索。
(9)第九天:商品詳情頁面的展現。
(10)第十天:單點登陸系統。Session共享。
(11)第十一天:購物車訂單系統的實現。
(12)第十二天:nginx。反向代理工具。
(13)第十三天:redis集羣的搭建、solr集羣的搭建。系統的部署。
(14)項目總結。html
第五天時候,咱們已經把淘淘商城的門戶系統、服務系統建立、啓動並正常訪問,那麼今天咱們將把門戶系統、服務系統的相關業務邏輯進行編寫,功能包括首頁的動態實現、CMS 內容管理、首頁大廣告等內容,下面主要講解Httpclient使用,其餘的具體業務邏輯編寫,請在參考資料下載中進行學習。java
HTTP 協議多是如今 Internet 上使用得最多、最重要的協議了,愈來愈多的 Java 應用程序須要直接經過 HTTP 協議來訪問網絡資源。雖然在 JDK 的 java net包中已經提供了訪問 HTTP 協議的基本功能,可是對於大部分應用程序來講,JDK 庫自己提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,而且它支持 HTTP 協議最新的版本和建議。 下載地址:http://hc.apache.org/nginx
如下列出的是 HttpClient 提供的主要的功能,要知道更多詳細的功能能夠參見 HttpClient 的主頁。
(1)實現了全部 HTTP 的方法(GET,POST,PUT,HEAD 等)
(2)支持自動轉向
(3)支持 HTTPS 協議
(4)支持代理服務器等redis
3.1 導入依賴spring
<!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version> </dependency>
3.2 無參的GET請求apache
public class DoGET { public static void main(String[] args) throws Exception { // 建立Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 建立http GET請求 HttpGet httpGet = new HttpGet("http://www.baidu.com/"); CloseableHttpResponse response = null; try { // 執行請求 response = httpclient.execute(httpGet); // 判斷返回狀態是否爲200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println("內容長度:" + content.length()); // FileUtils.writeStringToFile(new File("C:\\baidu.html"), content); } } finally { if (response != null) { response.close(); } httpclient.close(); } } }
3.3 帶參數的get請求編程
public class DoGETParam { public static void main(String[] args) throws Exception { // 建立Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 定義請求的參數 URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build(); System.out.println(uri); // 建立http GET請求 HttpGet httpGet = new HttpGet(uri); CloseableHttpResponse response = null; try { // 執行請求 response = httpclient.execute(httpGet); // 判斷返回狀態是否爲200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } httpclient.close(); } } }
3.4 不帶參數的post請求json
public class DoPOST { public static void main(String[] args) throws Exception { // 建立Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 建立http POST請求 HttpPost httpPost = new HttpPost("http://www.oschina.net/"); CloseableHttpResponse response = null; try { // 執行請求 response = httpclient.execute(httpPost); // 判斷返回狀態是否爲200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } httpclient.close(); } } }
3.5 帶參數的post請求緩存
public class DoPOSTParam { public static void main(String[] args) throws Exception { // 建立Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 建立http POST請求 HttpPost httpPost = new HttpPost("http://www.oschina.net/search"); // 設置2個post參數,一個是scope、一個是q List<NameValuePair> parameters = new ArrayList<NameValuePair>(0); parameters.add(new BasicNameValuePair("scope", "project")); parameters.add(new BasicNameValuePair("q", "java")); // 構造一個form表單式的實體 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); // 將請求實體設置到httpPost對象中 httpPost.setEntity(formEntity); CloseableHttpResponse response = null; try { // 執行請求 response = httpclient.execute(httpPost); // 判斷返回狀態是否爲200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } httpclient.close(); } } }
3.6 封裝HttpClient通用工具類
在taotao-common項目中,導入maven依賴後,新建HttpClientUtil.java
package com.taotao.common.utils;
import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /** * 定義網絡請求相關內容 * * @author Administrator * */ public class HttpClientUtil { /** * 帶集合參數的get請求 * @param url * @param param * @return */ 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; } /** * 不帶參數的get請求 */ public static String doGet(String url) { return doGet(url, null); } /** * 帶集合參數的post請求 * @param url * @param param * @return */ 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<NameValuePair>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模擬表單 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); 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; } /** * 不帶參數的get請求 */ public static String doPost(String url) { return doPost(url, null); } /** * 帶json字符串參數的post請求 * * @param url * @param json * @return */ 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; } }
3.7 HttpClient的使用
在taotao-portal項目的ContentServiceImpl.java中進行使用
package com.taotao.portal.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.taotao.common.pojo.TaotaoResult; import com.taotao.common.utils.HttpClientUtil; import com.taotao.pojo.TbContent; import com.taotao.portal.service.ContentService; @Service public class ContentServiceImpl implements ContentService { @Value("${SERVICE_BASE_URL}") private String SERVICE_BASE_URL ; @Value("${INDEX_AD1_URL}") private String INDEX_AD1_URL ; @Override public List<TbContent> getContentList(long categoryId) { //調用服務層的服務 String resStr = HttpClientUtil.doGet(SERVICE_BASE_URL + INDEX_AD1_URL + categoryId); //把字符串轉換成java對象 TaotaoResult result = TaotaoResult.formatToList(resStr, TbContent.class); if (result.getStatus() == 200) { List<TbContent> listContent = (List<TbContent>) result.getData(); return listContent; } return null; } }
連接:https://pan.baidu.com/s/1Q8HP8l_2WxWAGFrCptHg0w
提取碼:iuq5