Spring MVC Management httpclient---Implementation to send requests directly to controller in Java

Source: Internet
Author: User
Tags aop

In spring MVC, most of the time a client's page sends a request to the controller, such as Ajax, but sometimes it is necessary to send a request directly to the controller in Java code, where httpcilent implementations can be used.

The first package to use is Httpclient-4.3.5.jar and Httpcore-4.3.2.jar.

First look at the following code:

[Java] View Plain copy print? 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 {        /**       *  processing GET request .        *  @param  url   Request path        *  @return    json       */       public String  Get (String url) {           //instantiation httpclient           CloseableHttpClient httpclient =  Httpclients.createdefault ();           //instantiation Get Method            httpget httpget = new httpget (URL);     &NBSP;&Nbsp;      //Request Results             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");               &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (content);               }            } catch  (clientprotocolexception e)  {               e.printstacktrace ();            } catch  (ioexception e)  {                e.printstacktrace ();            }           return  content;       }       /**        *  processing POST request .       *  @param  url   Request path        *  @param  params   Parameters        *   @return &NBsp; json       */       public string  post (string url,map<string, string> params) {            //instantiation httpclient            Closeablehttpclient httpclient = httpclients.createdefault ();            //materialized Post method            httppost  httppost = new httppost (URL);             //Processing Parameters            list<namevaluepair> nvps  = new ArrayList <NameValuePair> ();              set<string> keyset = params.keyset ();          &nBsp;  for (string key : keyset)  {                  nvps.add (New basicnamevaluepair) (Key, params.get (key) ));             }              //Results             closeablehttpresponse response = null;            string content= "";           try {                //submitted Parameters                 urlencodedformentity uefentity  =  new urlencodedformentity (nvps,  "UTF-8");                //the parameters to post methods                 Httppost.setentity (uefentity);                //perform post methods                response  = httpclient.execute (httppost);                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;       }        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 ();   &Nbsp;       map.put ("id", "1");            hd.post ("http://localhost:8080/springMVC/menu/getChildren.do", map);        }     }  

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;
 /** * handles HTTP requests in Java.
     * @author NAGSH * * */public class Httpdeal {/** * handles get requests. * @param URL Request path * @return JSON */Public String get (string url) {//instantiated httpclient closeablehttpclient HT
		Tpclient = 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;
	 /** * Processes post requests. * @param URL Request path * @param params parameter * @return JSON */public string post (string url,map<string, string> p
		Arams) {//instantiate httpclient closeablehttpclient 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)); }//Results CloseablehttpresPonse response = null;
		String content= "";
			try {//submit parameters Urlencodedformentity Uefentity = new Urlencodedformentity (Nvps, "UTF-8");
			Give the parameter to the Post method httppost.setentity (uefentity);
			Executes the Post method response = Httpclient.execute (HttpPost);
				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;
        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 be used to implement both gets and post requests, and if it is not a problem to run in a Java test class alone, it will throw an exception if invoked in controller or JSP. Why, then? Since it's in SPRINGMVC, we should give it to spring to manage.

First of all: Httpclient-servlet.xml

[HTML] View Plain copy print? <?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.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ spring-context-4.0.xsd       http://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.xsd       http://www.springframework.org/schema/util http://www.springframework.org/schema/ Util/spring-util-4.0.xsd ">       <!--  Configuration Placeholder  -->       <bean           class= " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ">            <property name= "Location"  value= "Classpath:/httpclient.properties"  />       </bean>       <!--  Define HttpClient Connection Pool  -->       <bean id= "Httpclientconnectionmanager"  class= "org.apache.http.impl.coNn. Poolinghttpclientconnectionmanager " destroy-method=" Close ">            <!--  Set total number of connections  -->            <property name= "Maxtotal"  value= "${http.pool.maxtotal}" ></property>            <!--  Set concurrent number for each address  -->            <property name= "Defaultmaxperroute"  value= "${ Http.pool.defaultMaxPerRoute} "></property>       </bean>               <!--  definition  httpclient factory, This 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 example  -->       <bean id= "HttpClient"  factory-bean= "Httpclientbuilder"  factory-method= "Build"/>               <!--  Regular cleanup of invalid connections  -->       < bean class= "Module.system.common.IdleConnectionEvictor"  destroy-method= "Shutdown" >           <constructor-arg index= "0"  ref= " Httpclientconnectionmanager " />           <!--   Interval One-minute cleanup  -->           <constructor-arg  index= "1"  value= "60000"  />       </bean>               <!--  Define Requestconfig factory  -->       <bean  id= "Requestconfigbuilder"  class= "Org.apache.http.client.config.RequestConfig.Builder" >            <!--  Maximum time to connect from connection pool  -->           <property name= "Connectionrequesttimeout"  v

Related Article

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.