Spring integration HttpClient Implementing Cross-domain requests

Source: Internet
Author: User

Before configuring the spring integration httpclient, let's talk about Jsonp, a Cross-domain request based on the SRC attribute of the page script tag, which has a two-point disadvantage compared to HTTPCLIENT,JSONP, which, first of all, can only send a GET request, If sending a POST request can cause the request to fail to resolve the problem of not getting the data, moreover, if the returned data you do not have to configure the corresponding coding file to deal with you will be a bunch of garbled, the problem for httpclient is not so many constraints, he is a package of HTTP protocol jar package , the basic request method gets post put delete he can achieve, Of course, you have to configure the appropriate filter interceptor in the Web.xml file to intercept the request and then set the code, the general return parameters are JSON strings, and we just need to import Jackson or Flexjson or other jar package to parse the object to convert him to the data you need. Here's a specific configuration for httpclient and spring integration, not much more directly on the code:

lead Dependence

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId> httpclient</artifactid>
    <version>4.5.2</version>
</dependency>

applicationcontext.xml file Import httpclient.properties

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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-4.0.xsd http://www.springframework.org/schema/util http:// Www.springframework.org/schema/util/spring-util-4.0.xsd "> <!--configuration annotation Scanner-->; Context:component-scan base-package= "Com.lyt.usermanage.service"/> <!--load resource file--> <bean class= "org.  Springframework.beans.factory.config.PropertyPlaceholderConfigurer > <!--Configure the resource file--> <property
                Name= "Locations" > <list> <value>classpath:jdbc.properties</value>
    <value>classpath:httpclient.properties</value> </list> </property> </bean> <!--Configure connection pooling, data source--> <bean id= "DataSource class=" Com.mchange.v2.c3p0.ComboPooledDataSourc
        E "destroy-method=" close "> <property name=" driverclass "value=" ${driver} "></property> <property name= "Jdbcurl" value= "${url}" ></property> <property name= "user" value= "${username}" ;</property> <property name= "password" value= "${password}" ></property> </bean> </be Ans>

spring-httpclient.xml Configuration

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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 "> <!--definition httpclient CompanyConnect the 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 concurrent per address--> 

    <property name= "Defaultmaxperroute" value= "${http.pool.defaultmaxperroute}" ></property> </bean> <!--define HttpClient factory, where Httpclientbuilder is used to build--> <bean id= "Httpclientbuilder" class= "Org.apache.http.imp" L.client.httpclientbuilder "factory-method=" create "> <property name=" ConnectionManager "ref=" HttpClientConne Ctionmanager "></property> </bean> <!--get httpclient instance--> <bean id=" httpclient "fact Ory-bean= "Httpclientbuilder" factory-method= "Build"/> <!--periodically cleans invalid connections--> <bean class= "Com.lyt.userman Age.thread.IdleConnectionEvictor "destroy-method=" Shutdown "> <construCtor-arg index= "0" ref= "Httpclientconnectionmanager"/> <constructor-arg index= "1" value= "${http.maxIdleTime} 
    "/> <constructor-arg index=" 2 "value=" MINUTES "/> </bean> <!--define Requestconfig factory--> <bean id= "Requestconfigbuilder" class= "Org.apache.http.client.config.RequestConfig.Builder" > <!-- Maximum time--> <property name= "connectionrequesttimeout" value= "${http.request.connectionrequesttimeout}" in the pool for which the connection was fetched /> <!--maximum time to create a connection--> <property name= "ConnectTimeout" value= "${http.request.connecttimeout}"/&
        Gt <!--maximum time for data transfer--> <property name= "sockettimeout" value= "${http.request.sockettimeout}"/> < Test the connection for--> <property name= "staleconnectioncheckenabled value=" before submitting the request!--${HTTP.REQUEST.STALECONNECTIONCHEC kenabled} "/> </bean> <!--get Requestconfig instance--> <bean id=" Requestconfig "factory-bean=" req UestconfigbuIlder "factory-method=" Build "/> </beans> </beans>
 

httpclient.properties File Configuration

#从连接池中获取到连接的最长时间
http.request.connectionrequesttimeout=500
#设置链接超时
http.request.connecttimeout= 5000
#数据传输的最长时间
http.request.sockettimeout=30000
#提交请求前测试连接是否可用
Http.request.staleconnectioncheckenabled=true
#设置连接总数
http.pool.maxtotal=200
#设置每个地址的并发数
http.pool.defaultmaxperroute=100
#设置定时清除无效链接时间
http.maxidletime=1

Clear Invalid link wiring class

Package com.lyt.common.httpclient;

Import Org.apache.http.conn.HttpClientConnectionManager;

public class Idleconnectionevictor extends Thread {

    private final httpclientconnectionmanager connmgr;

    Private volatile Boolean shutdown;

    Public Idleconnectionevictor (Httpclientconnectionmanager connmgr) {
        this.connmgr = connmgr;
        This.start ();
    }

    @Override public
    Void Run () {a
        try {while
            (!shutdown) {
                synchronized (.) {wait
                    (5000);
                    Turn off Invalid connection
                    connmgr.closeexpiredconnections ();} \
        catch (Interruptedexception ex) {
            //end
        }
    }

    public void shutdown () {
        shutdown = true;
        Synchronized (this) {
            notifyall ();}}}


The specific label attributes are made note, set to what you need. And I've got a problem, and that's what I wrote myself. Clear the thread class of the invalid link cannot have the bean file in the way configured in the consolidated file without knowing why. Ask the great God to answer, the newspaper error is:

Finally, the encapsulation of the HttpClient tool class for the doget () and Dopost () request method is directly on the code:

Package com.lyt.usermanage.service;
Import java.io.IOException;
Import java.net.URISyntaxException;
Import java.util.ArrayList;
Import java.util.List;

Import Java.util.Map;
Import Org.apache.commons.lang3.StringUtils;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.ClientProtocolException;
Import Org.apache.http.client.config.RequestConfig;
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.message.BasicNameValuePair;
Import Org.apache.http.util.EntityUtils;
Import org.springframework.beans.BeansException;
Import Org.springframework.beans.factory.BeanFactory; Import ORG.SPRINGFRAMEWORK.BEANS.FActory.
Beanfactoryaware;
Import org.springframework.beans.factory.annotation.Autowired;

Import Org.springframework.stereotype.Service;

Import Com.lyt.usermanage.model.HttpResult; /** * Dedicated HTTP request * @author Administrator * */@Service public class Apiservice implements beanfactoryaware{/* @Aut

owired private closeablehttpclient httpclient;
    * * @Autowired (required=false) private requestconfig requestconfig; /** * * @return response body content * @throws IOException * @throws clientprotocolexception * * Public S Tring doget (String url) throws Clientprotocolexception, ioexception{//create HTTP GET request HttpGet HttpGet = NE
        W httpget (URL);
        Httpget.setconfig (Requestconfig)//Set request parameter closeablehttpresponse response = NULL;
            try {//Execute request response = This.gethttpclient (). Execute (httpget);
               Determines whether the return status is Response.getstatusline (). Getstatuscode () = 200) { String content = entityutils.tostring (response.getentity (), "UTF-8");
                System.out.println ("Content Length:" +content.length ());
            return content;
            Finally {if (response!= null) {response.close ());
        }//httpclient.close ();
    return null; /** * A GET request with parameters * @param URL * @return * @throws urisyntaxexception * @throws ioexceptio n * @throws clientprotocolexception */public string doget (string url, map<string, string> params)
        Throws URISyntaxException, Clientprotocolexception, ioexception{uribuilder uribuilder = new UriBuilder (URL); if (params!= null) {for (String Key:params.keySet ()) {Uribuilder.setparameter (key, param
            S.get (key));
    }//http://xxx?ss=ss return This.doget (Uribuilder.build (). toString ()); /** * POST request with parameters * @param URL * @param params * @return * @throws IOException * @throws clientprotocolexception/P


        Ublic httpresult doPost (String URL, map<string, string> params) throws Clientprotocolexception, ioexception{
        Create an HTTP POST request HttpPost HttpPost = new HttpPost (URL);
        Httppost.setconfig (Requestconfig); if (params!= null) {//Set 2 post parameters, one is scope, one is q list<namevaluepair> parameters = new Arrayl

            ist<namevaluepair> (0);
            For (String Key:params.keySet ()) {Parameters.Add (New Basicnamevaluepair (Key, Params.get (key));
            }//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 = This.gethttpclient (). Execute (HttpPost); Determines whether the return status is/*if (Response.getstatusline (). Getstatuscode () = = = {String content = Enti
                Tyutils.tostring (Response.getentity (), "UTF-8");
            SYSTEM.OUT.PRINTLN (content); }*/return to New Httpresult (Response.getstatusline (). Getstatuscode (), Entityutils.tostring (Response.getentity (),
        "UTF-8"));
            Finally {if (response!= null) {response.close ();
        }//httpclient.close ();
         } Public httpresult Dopostjson (string URL, string json) throws Clientprotocolexception, ioexception{
        Create an HTTP POST request HttpPost HttpPost = new HttpPost (URL);
        Httppost.setconfig (Requestconfig); if (Stringutils.isnotblank (JSON)) {//identifies the passed parameter is Application/json stringentity stringentity = new STR
            Ingentity (JSON, Contenttype.application_json);
        Httppost.setentity (stringentity); } closeablEhttpresponse response = null;
            try {//Execute request response = This.gethttpclient (). Execute (httppost); Determines whether the return status is/*if (Response.getstatusline (). Getstatuscode () = = = {String content = Enti
                Tyutils.tostring (Response.getentity (), "UTF-8");
            SYSTEM.OUT.PRINTLN (content); }*/return to New Httpresult (Response.getstatusline (). Getstatuscode (), Entityutils.tostring (Response.getentity (),
        "UTF-8"));
            Finally {if (response!= null) {response.close ();
        }//httpclient.close ();  }/** * POST request with no parameters * @throws IOException * @throws clientprotocolexception/Public
    Httpresult doPost (String url) throws Clientprotocolexception, ioexception{return this.dopost (URL, null);

    Private Beanfactory beanfactory; @Override public void Setbeanfactory (beanfactory beanfactory) tHrows beansexception {this.beanfactory = beanfactory;
    Private Closeablehttpclient gethttpclient () {return This.beanFactory.getBean (Closeablehttpclient.class);
 }
}

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.