對外的介面服務
我們把上一篇:【SSM分布式架構電商項目-14】後台CMS內容管理系統管理前台首頁廣告裡面的ContentController拷貝到api包下,對外提供介面服務:
package com.taotao.manage.controller.api;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import com.taotao.common.bean.EasyUIResult;import com.taotao.manage.service.ContentService;@RequestMapping("api/content")@Controllerpublic class ApiContentController { @Autowired private ContentService contentService; /** * 根據內容分類id查詢分類列表 * * @param categoryId * @param page * @param rows * @return */ @RequestMapping(method = RequestMethod.GET) public ResponseEntity<EasyUIResult> queryListByCategoryId(@RequestParam("categoryId") Long categoryId, @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "rows", defaultValue = "10") Integer rows) { try { EasyUIResult easyUIResult = this.contentService.queryListByCategoryId(categoryId, page, rows); return ResponseEntity.ok(easyUIResult); } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); }}
測試:
提供者服務的方式
方式有2種:
1、 js訪問
a) 有跨域 – jsonp解決
b) 無跨域 – ajax解決
2、 Java代碼訪問
a) Httpclient Httpclient
匯入依賴
DoGET
package cn.itcast.httpclient;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;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/s?wd=java"); 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(); } }}
帶有參數的GET請求
package cn.itcast.httpclient;import java.net.URI;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.utils.URIBuilder;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;public class DoGETParam { public static void main(String[] args) throws Exception { // 建立Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 定義請求的參數 URI uri = new URIBuilder("http://manage.taotao.com/rest/api/content").setParameter("categoryId", "33") .setParameter("page", "1").setParameter("rows", "1").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(); } }}
DoPOST
package cn.itcast.httpclient;import java.util.ArrayList;import java.util.List;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.HttpPost;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;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"); // 偽裝成瀏覽器 httpPost.setHeader( "User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36"); // 設定2個post參數,一個是scope、一個是q List<NameValuePair> parameters = new ArrayList<NameValuePair>(0); parameters.add(new BasicNameValuePair("scope", "project")); parameters.add(new BasicNameValuePair("q", "java")); parameters.add(new BasicNameValuePair("fromerr", "7nXH76r7")); // 構造一個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(); } }}
帶有參數的POST請求
public static void main(String[] args) throws Exception { // 建立Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 建立http POST請求 HttpPost httpPost = new HttpPost("http://www.oschina.net/search"); // 偽裝成瀏覽器 httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36"); // 設定2個post參數,一個是scope、一個是q List<NameValuePair> parameters = new ArrayList<NameValuePair>(0); parameters.add(new BasicNameValuePair("scope", "project")); parameters.add(new BasicNameValuePair("q", "java")); parameters.add(new BasicNameValuePair("fromerr", "7nXH76r7")); // 構造一個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(); } }
連線管理員
注意:
package cn.itcast.httpclient;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.conn.HttpClientConnectionManager;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.util.EntityUtils;public class HttpConnectManager { public static void main(String[] args) throws Exception { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); // 設定最大串連數 cm.setMaxTotal(200); // 設定每個主機地址的並發數 cm.setDefaultMaxPerRoute(20); doGet(cm); doGet(cm); } public static void doGet(HttpClientConnectionManager cm) throws Exception { CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); // 建立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()); } } finally { if (response != null) { response.close(); } // 此處不能關閉httpClient,如果關閉httpClient,串連池也會銷毀 // httpClient.close(); } }}
定期關閉無效串連
public class ClientEvictExpiredConnections { public static void main(String[] args) throws Exception { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); // 設定最大串連數 cm.setMaxTotal(200); // 設定每個主機地址的並發數 cm.setDefaultMaxPerRoute(20); new IdleConnectionEvictor(cm).start(); } public static class IdleConnectionEvictor extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionEvictor(HttpClientConnectionManager connMgr) { this.connMgr = connMgr; } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // 關閉失效的串連 connMgr.closeExpiredConnections(); } } } catch (InterruptedException ex) { // 結束 } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } }}
佈建要求參數
Httpclient和Spring的整合
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http