External Interface Services
We put on an article: "SSM Distributed architecture e-commerce project-14" Background CMS Content Management System Management front page ads inside the Contentcontroller copy to the API package, external interface services:
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") @Controller public class Apicontentcontroller {@Autowired private contentservice
Contentservice;
/** * Query category list based on content category ID * * @param categoryId * @param page * @param rows * @return * * @RequestMapping (method = requestmethod.get) public responseentity<easyuiresult> Querylistbycategoryid (@Reque Stparam ("CategoryId") Long categoryId, @RequestParam (value = "Page", DefAultvalue = "1") integer page, @RequestParam (value = "Rows", DefaultValue = "ten") 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);
}
}
Test:
How to access the interface service
There are 2 types of methods:
1. JS Access
A) a cross-domain –JSONP solution
b) No cross-domain –ajax resolution
2. Java code Access
A) Httpclient Httpclient
Import Dependency
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 {//Create HttpClient Object Clo
Seablehttpclient httpclient = Httpclients.createdefault ();
Create an HTTP GET request HttpGet HttpGet = new HttpGet ("Http://www.baidu.com/s?wd=java");
Closeablehttpresponse response = null;
try {//Execute request response = Httpclient.execute (HttpGet); Determines whether the return status is a Response.getstatusline (). Getstatuscode () = = () {String content = Entity
Utils.tostring (Response.getentity (), "UTF-8");
System.out.println ("content:" +content);
}} finally {if (response! = NULL) { Response.close ();
} httpclient.close ();
}
}
}
GET request with parameters
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 {//Create HttpClient Object
Closeablehttpclient httpclient = Httpclients.createdefault ();
Defines the request's parameter 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);
Create an HTTP GET request HttpGet HttpGet = new HttpGet (URI);
Closeablehttpresponse response = null;
try {//Execute request response = Httpclient.execute (HttpGet); //Determine if the return status is a Response.getstatusline (). Getstatuscode () = = () {String content = Entityu
Tils.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 {//Create HttpClient Object
Closeablehttpclient httpclient = Httpclients.createdefault ();
Create an HTTP POST request HttpPost HttpPost = new HttpPost ("Http://www.oschina.net/search"); masquerading as browser 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 "); Set 2 postParameters, one is scope, one is 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"));
Construct a form-form entity urlencodedformentity formentity = new urlencodedformentity (parameters);
Set the request entity to the HttpPost object Httppost.setentity (formentity);
Closeablehttpresponse response = null;
try {//Execute request response = Httpclient.execute (HttpPost); Determines whether the return status is a Response.getstatusline (). Getstatuscode () = = () {String content = Entity
Utils.tostring (Response.getentity (), "UTF-8");
SYSTEM.OUT.PRINTLN (content);
}} finally {if (response! = null) {response.close ();
} httpclient.close (); }
}
}
POST request with parameters
public static void Main (string[] args) throws Exception {//Create HttpClient object Closeablehttpclient Httpclie
NT = Httpclients.createdefault ();
Create an HTTP POST request HttpPost HttpPost = new HttpPost ("Http://www.oschina.net/search"); masquerading as browser 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 ");
Set 2 post parameters, one is scope, one is 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"));
Construct a form-form entity urlencodedformentity formentity = new urlencodedformentity (parameters);
Set the request entity to the HttpPost object Httppost.setentity (formentity);
Closeablehttpresponse response = null;
try { Execution Request response = Httpclient.execute (HttpPost); Determines whether the return status is a Response.getstatusline (). Getstatuscode () = = () {String content = Entity
Utils.tostring (Response.getentity (), "UTF-8");
SYSTEM.OUT.PRINTLN (content);
}} finally {if (response! = null) {response.close ();
} httpclient.close ();
}
}
Connection Manager
Attention:
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 {Poolinghttpclient
ConnectionManager cm = new Poolinghttpclientconnectionmanager ();
Set maximum number of connections cm.setmaxtotal (200);
Sets the number of concurrent Cm.setdefaultmaxperroute (20) for each host address;
Doget (CM);
Doget (CM); } public static void Doget (Httpclientconnectionmanager cm) throws Exception {closeablehttpclient httpClient
= Httpclients.custom (). Setconnectionmanager (CM). Build (); Create an HTTP GET request HttpGet HttpGet = new HttpGet ("http://www.baidu.com/");
Closeablehttpresponse response = null;
try {//Execute request response = Httpclient.execute (HttpGet); Determines whether the return status is a Response.getstatusline (). Getstatuscode () = = () {String content = Entity
Utils.tostring (Response.getentity (), "UTF-8");
System.out.println ("Content length:" + content.length ());
}} finally {if (response! = null) {response.close ();
}//cannot close httpClient here, if HttpClient is turned off, the connection pool will also be destroyed//Httpclient.close ();
}
}
}
Close Invalid connections periodically
public class Clientevictexpiredconnections {public static void main (string[] args) throws Exception {Poolin
Ghttpclientconnectionmanager cm = new Poolinghttpclientconnectionmanager ();
Set maximum number of connections cm.setmaxtotal (200);
Sets the number of concurrent Cm.setdefaultmaxperroute (20) for each host address;
New Idleconnectionevictor (cm). Start (); } public static class Idleconnectionevictor extends Thread {private final Httpclientconnectionmanager connm
Gr
Private volatile Boolean shutdown;
Public Idleconnectionevictor (Httpclientconnectionmanager connmgr) {this.connmgr = Connmgr;
} @Override public void Run () {try {while (!shutdown) {
Synchronized (this) {Wait (5000);
Close the failed connection connmgr.closeexpiredconnections (); }}} catch (InterruptedexCeption ex) {//end}} public void Shutdown () {shutdown = true;
Synchronized (this) {notifyall ();
}
}
}
}
Set Request Parameters
integration of httpclient and 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