Springboot using OKHTTP3

Source: Internet
Author: User

1. Adding Pom.xml dependencies

        <dependency>            <groupId>com.squareup.okhttp3</groupId>            <artifactid>okhttp</ artifactid>            <version>3.6.  0</version>        </dependency>

2. Configuration Classes

Import Java.security.keymanagementexception;import Java.security.nosuchalgorithmexception;import Java.security.securerandom;import Java.security.cert.certificateexception;import Java.security.cert.x509certificate;import Java.util.concurrent.timeunit;import Javax.net.ssl.SSLContext;import Javax.net.ssl.sslsocketfactory;import Javax.net.ssl.trustmanager;import Javax.net.ssl.x509trustmanager;import OKHTTP3. Connectionpool;import OKHTTP3. Okhttpclient;import Org.springframework.context.annotation.bean;import org.springframework.context.annotation.Configuration;/** * Created by Qhong on 2018/7/3 16:52 **/@Configuration Public classOkhttpconfig {@Bean PublicX509trustmanager X509trustmanager () {return NewX509trustmanager () {@Override Public voidcheckclienttrusted (x509certificate[] x509certificates, String s) throws certificateexception {} @Override Public voidcheckservertrusted (x509certificate[] x509certificates, String s) throws certificateexception {} @Override Publicx509certificate[] Getacceptedissuers () {return Newx509certificate[0];    }        }; } @Bean Publicsslsocketfactory sslsocketfactory () {Try {            //Trust any linkSslcontext Sslcontext = sslcontext.getinstance ("TLS"); Sslcontext.init (NULL,NewTrustmanager[]{x509trustmanager ()},Newsecurerandom ()); returnsslcontext.getsocketfactory (); } Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(keymanagementexception e) {e.printstacktrace (); }        return NULL; }    /** * Create A new connection pool with tuning parameters appropriate for a single-user application. * The tuning parameters in this pool is subject to change in the future OkHttp releases. Currently*/@Bean PublicConnectionPool Pool () {return NewConnectionPool ( $,5, timeunit.minutes); } @Bean Publicokhttpclient okhttpclient () {return NewOkhttpclient.builder (). Sslsocketfactory (Sslsocketfactory (), X509trustmanager ()). Retry Onconnectionfailure (false)//whether to turn on caching. ConnectionPool (Pool ())//Connection Pool. ConnectTimeout (10L, Timeunit.seconds). ReadTimeout (10L, Timeunit.seconds). Build (); }}

3. Tool Class:

import Java.util.iterator;import java.util.map;import okhttp3. Formbody;import OKHTTP3. Mediatype;import OKHTTP3. Okhttpclient;import OKHTTP3. Request;import OKHTTP3. Requestbody;import OKHTTP3. Response;import Org.apache.commons.lang3.exception.exceptionutils;import Org.slf4j.logger;import Org.slf4j.LoggerFactory;/** * Created by Qhong on 2018/7/3 16:55 **/ Public classokhttputil{Private StaticFinal Logger Logger = Loggerfactory.getlogger (okhttputil.class); /** * Get GET request parameters according to map * @param queries * @return*/    Private StaticStringBuffer getquerystring (String url,map<string,string>queries) {StringBuffer SB=Newstringbuffer (URL); if(Queries! =NULL&& queries.keyset (). Size () >0) {Boolean Firstflag=true; Iterator Iterator=Queries.entryset (). iterator ();  while(Iterator.hasnext ()) {Map.entry Entry= (map.entry<string, string>) Iterator.next (); if(Firstflag) {sb.append ("?"+ Entry.getkey () +"="+Entry.getvalue ()); Firstflag=false; } Else{sb.append ("&"+ Entry.getkey () +"="+Entry.getvalue ()); }            }        }        returnSB; }    /** * Call Okhttp's Newcall method * @param request * @return*/    Private StaticString Execnewcall (Request request) {Response Response=NULL; Try{okhttpclient okhttpclient=Newokhttpclient (); Response=Okhttpclient.newcall (Request). Execute (); intStatus =Response.code (); if(Response.issuccessful ()) {returnResponse.body ().string(); }        } Catch(Exception e) {logger.error ("OKHTTP3 put error >> ex = {}", Exceptionutils.getstacktrace (e)); } finally {            if(Response! =NULL) {response.close (); }        }        return ""; }    /** * get * @param URL request URL * @param queries request parameters in the browser? After the data, no null can be passed * @return*/     Public StaticStringGet(String URL, map<string, string>queries) {StringBuffer SB=getquerystring (url,queries); Request Request=Newrequest.builder (). URL (sb.tostring ()). build (); returnExecnewcall (Request); }    /** * post * * @param URL requested by * @param params post form parameter * @return*/     Public StaticString postformparams (string url, map<string, string>params) {Formbody.builder Builder=NewFormbody.builder (); //Adding Parameters        if(params!=NULL&&params. KeySet (). Size () >0) {             for(String key:params. KeySet ()) {Builder.add (Key,params.Get(key)); }} Request Request=Newrequest.builder (). URL (URL). Post (Builder.build ()). build (); returnExecnewcall (Request); }    /** * POST request to send JSON data .... {"Name": "Zhangsan", "pwd": "123456"} * parameter one: request URL * Parameter two: JSON for request * parameter three: request callback*/     Public Staticstring postjsonparams (string url, string jsonparams) {requestbody requestbody= Requestbody.create (Mediatype.parse ("Application/json; Charset=utf-8"), jsonparams); Request Request=Newrequest.builder (). URL (URL). Post (Requestbody). build (); returnExecnewcall (Request); }    /** * POST request to send XML data .... * Parameter one: request URL * parameter two: request xmlstring * parameter three: request callback*/     Public Staticstring postxmlparams (string URL, string xml) {requestbody requestbody= Requestbody.create (Mediatype.parse ("application/xml; Charset=utf-8"), XML); Request Request=Newrequest.builder (). URL (URL). Post (Requestbody). build (); returnExecnewcall (Request); }}

https://miaoxinwei.github.io/2017/04/21/spring-%E9%9B%86%E6%88%90-okhttp3/

79714375

Https://www.programcreek.com/java-api-examples/?code=hjw541988478/OkHttpTutorial/OkHttpTutorial-master/app/src /main/java/in/harvestday/okhttpdemo/okhttputil.java

Https://github.com/guozhengXia/OkHttpUtils

Https://github.com/hongyangAndroid/okhttputils

Springboot using OKHTTP3

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.