Spring MVC Management HttpClient---Implementation sends requests directly to the controller in Java

Source: Internet
Author: User

In spring MVC, most of the time, the client's page sends requests to the controller via Ajax, but sometimes it needs to send a request directly to the controller in Java code, which can be implemented using Httpcilent.

The first packages used are Httpclient-4.3.5.jar and Httpcore-4.3.2.jar.

Let's look at the following code:

Package Module.system.common;import Java.io.ioexception;import Java.util.arraylist;import java.util.HashMap;import Java.util.list;import Java.util.map;import Java.util.set;import Org.apache.http.namevaluepair;import Org.apache.http.client.clientprotocolexception;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.impl.client.closeablehttpclient;import Org.apache.http.impl.client.httpclients;import Org.apache.http.message.basicnamevaluepair;import org.apache.http.util.entityutils;/** * Processing HTTP requests in Java.     * @author NAGSH * */public class Httpdeal {/** * handles get requests.  * @param URL Request path * @return JSON */public string get (string url) {//instantiation httpclientcloseablehttpclient httpclient = Httpclients.createdefault ();//Instantiate get method HttpGet HttpGet = new HttpGet (URL); Request result Closeablehttpresponse response = null; STring content = "", try {//execute get method response = Httpclient.execute (HttpGet), if (Response.getstatusline (). Getstatuscode () = =200) {content = Entityutils.tostring (response.getentity (), "utf-8"); SYSTEM.OUT.PRINTLN (content);}} catch (Clientprotocolexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return content;} /** * Processing Post requests. * @param URL Request path * @param params parameter * @return JSON */public string Post (string url,map<string, string> params) {/ /instantiation Httpclientcloseablehttpclient httpclient = Httpclients.createdefault ();//Instantiate post method HttpPost HttpPost = new HttpPost (URL);          Processing parameters list<namevaluepair> Nvps = new ArrayList <NameValuePair> ();      set<string> KeySet = Params.keyset ();      for (String key:keyset) {nvps.add (New Basicnamevaluepair (Key, Params.get (key))); }//Result closeablehttpresponse response = null; String content= ""; try {//submit parameter Urlencodedformentity uefentity = new Urlencodedformentity (Nvps, "UTF-8");// Give the parameter to the POST method Httppost.seteNtity (uefentity);//execute post Method response = Httpclient.execute (HttpPost); Response.getstatusline () = = () {content = Entityutils.tostring (response.getentity (), "utf-8"); SYSTEM.OUT.PRINTLN (content);}} catch (Clientprotocolexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return content;}        public static void Main (string[] args) {httpdeal HD = new Httpdeal ();        Hd.get ("http://localhost:8080/springMVC/userType/getAll.do");        map<string,string> map = new HashMap ();        Map.put ("id", "1"); Hd.post ("http://localhost:8080/springMVC/menu/getChildren.do", map);}}
The Get and post methods in this class can implement get requests and post requests, respectively, if running inside a Java test class is not a problem, but is called in a controller or JSP, it throws an exception. Why is it? Because it is in the SPRINGMVC, we should give it to spring to manage it.

The first is: Httpclient-servlet.xml

<?xml version= "1.0" encoding= "UTF-8"? ><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.xsdhttp://www.springframework.org/schema/context http ://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/aop http ://www.springframework.org/schema/aop/spring-aop-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/http Www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/util/HTTP Www.springframework.org/schema/util/spring-util-4.0.xsd "> <!--configuration placeholder--><beanclass=" Org.springframework.beans.factOry.config.PropertyPlaceholderConfigurer "><property name=" Location "value=" classpath:/ Httpclient.properties "/></bean><!--definition httpclient connection pool--><bean id=" Httpclientconnectionmanager " class= "Org.apache.http.impl.conn.PoolingHttpClientConnectionManager" destroy-method= "Close" ><!--set the total number of connections-- ><property name= "Maxtotal" value= "${http.pool.maxtotal}" ></property><!--set the number of concurrency per address-->< Property Name= "Defaultmaxperroute" value= "${http.pool.defaultmaxperroute}" ></property></bean>< !--define the HttpClient factory, which uses Httpclientbuilder to build--><bean id= "Httpclientbuilder" class= " Org.apache.http.impl.client.HttpClientBuilder "factory-method=" create "><property name=" ConnectionManager " ref= "Httpclientconnectionmanager" ></property></bean><!--get httpclient instance--><bean id= " HttpClient "factory-bean=" Httpclientbuilder "factory-method=" Build "/><!--periodically clean up invalid connections--><bean class=" Module.system.common.IdleConnectionEvIctor "destroy-method=" shutdown "><constructor-arg index=" 0 "ref=" Httpclientconnectionmanager "/><!-- Clean up once a minute--><constructor-arg index= "1" value= "60000"/></bean><!--defined Requestconfig factory-->< Bean id= "Requestconfigbuilder" class= "Org.apache.http.client.config.RequestConfig.Builder" ><!-- The maximum time to obtain a connection from the connection pool--><property name= "Connectionrequesttimeout" value= "${http.request.connectionrequesttimeout } "/><!--the maximum time to create a connection--><property name=" ConnectTimeout "value=" ${http.request.connecttimeout} "/><! --Maximum time for data transfer--><property name= "Sockettimeout" value= "${http.request.sockettimeout}"/><!-- Test if the connection is available before submitting the request--><property Name= "staleconnectioncheckenabled" value= "${ http.request.staleConnectionCheckEnabled} "/></bean><!--get Requestconfig instance--><bean id=" Requestconfig "factory-bean=" Requestconfigbuilder "factory-method=" Build "/></beans>

Httpclient.properties:

#从连接池中获取到连接的最长时间http. request.connectionrequesttimeout=500#5000http.request.connecttimeout=5000# Maximum time for data transfer http.request.sockettimeout=30000# test if the connection is available before submitting the request http.request.staleconnectioncheckenabled=true# Set total number of connections http.pool.maxtotal=200# set the number of concurrency per address http.pool.defaultmaxperroute=100


A required class, remember to modify the path of the class in XML:

package Module.system.common;import org.apache.http.conn.httpclientconnectionmanager;/** * Regular cleanup of invalid HTTP connections */public class Idleconnectionevictor extends        Thread {private final Httpclientconnectionmanager connmgr;    Private Integer WaitTime;    Private volatile Boolean shutdown;        Public Idleconnectionevictor (Httpclientconnectionmanager Connmgr,integer waitTime) {this.connmgr = connMgr;        This.waittime = WaitTime;    This.start ();                    } @Override public void Run () {try {while (!shutdown) {synchronized (this) {                    Wait (waitTime);                Close the failed connection connmgr.closeexpiredconnections (); }}} catch (Interruptedexception ex) {//end}}/** * Destroy release resources */Pub        LIC void shutdown () {shutdown = true;        Synchronized (this) {notifyall (); }    }}
Redeploy, you can instantiate the Httpdeal class in the controller and invoke its method. My spring MVC incorporates JSON, so the return value is JSON data, such as:

[{"id": 1, "type": "Administrator", "menu": "},{", "id": 2, "type": "Operator", "menu": "1, 2,"}] [{"id": 4, "attributes": null, "Children": [], "text": "User Management", "pid": 1, "url": ". /user/getpage.do "," title ": null," Ptext ":" System Management "},{" ID ": 5," attributes ": null," Children ": []," text ":" Department Management "," pid ": 1," URL ":". /department/getpage.do "," title ": null," Ptext ":" System Management "},{" ID ": Ten," attributes ": null," Children ": []," text ":" Rights Management "," pid ": 1," url ":". /usertype/getpage.do "," title ": null," Ptext ":" System Administration "}]

The JSON can be converted to a map using the method in my other article http://blog.csdn.net/u012116457/article/details/24371877.



Spring MVC Management HttpClient---Implementation sends requests directly to the controller in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.