欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于springboot的RestTemplate、okhttp和HttpClient对比分析

程序员文章站 2022-04-06 21:16:31
1、httpclient:代码复杂,还得操心资源回收等。代码很复杂,冗余代码多,不建议直接使用。2、resttemplate: 是 spring 提供的用于访问rest服务的客户端, resttemp...

1、httpclient:代码复杂,还得操心资源回收等。代码很复杂,冗余代码多,不建议直接使用。

2、resttemplate: 是 spring 提供的用于访问rest服务的客户端, resttemplate 提供了多种便捷访问远程http服务的方法,能够大大提高客户端的编写效率。

引入jar包:

  <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>

添加初始化配置(也可以不配,有默认的)--注意resttemplate只有初始化配置,没有什么连接池

package com.itunion.config;

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.http.client.clienthttprequestfactory;
import org.springframework.http.client.simpleclienthttprequestfactory;
import org.springframework.web.client.resttemplate;

@configuration
public class apiconfig {
    @bean
    public resttemplate resttemplate(clienthttprequestfactory factory) {
        return new resttemplate(factory);
    }

    @bean
    public clienthttprequestfactory simpleclienthttprequestfactory() {
        simpleclienthttprequestfactory factory = new simpleclienthttprequestfactory();//默认的是jdk提供http连接,需要的话可以//通过setrequestfactory方法替换为例如apache httpcomponents、netty或//okhttp等其它http library。
        factory.setreadtimeout(5000);//单位为ms
        factory.setconnecttimeout(5000);//单位为ms
        return factory;
    }
}

  1)get请求(不带参的即把参数取消即可)

// 1-getforobject()
user user1 = this.resttemplate.getforobject(uri, user.class);

// 2-getforentity()
responseentity<user> responseentity1 = this.resttemplate.getforentity(uri, user.class);
httpstatus statuscode = responseentity1.getstatuscode();
httpheaders header = responseentity1.getheaders();
user user2 = responseentity1.getbody();
  
// 3-exchange()
requestentity requestentity = requestentity.get(new uri(uri)).build();
responseentity<user> responseentity2 = this.resttemplate.exchange(requestentity, user.class);
user user3 = responseentity2.getbody();

    方式一:

notice notice = resttemplate.getforobject("http://fantj.top/notice/list/{1}/{2}"
                , notice.class,1,5);

    方式二:

map<string,string> map = new hashmap();
        map.put("start","1");
        map.put("page","5");
        notice notice = resttemplate.getforobject("http://fantj.top/notice/list/"
                , notice.class,map);

  2)post请求:

// 1-postforobject()
user user1 = this.resttemplate.postforobject(uri, user, user.class);

// 2-postforentity()
responseentity<user> responseentity1 = this.resttemplate.postforentity(uri, user, user.class);

// 3-exchange()
requestentity<user> requestentity = requestentity.post(new uri(uri)).body(user);
responseentity<user> responseentity2 = this.resttemplate.exchange(requestentity, user.class);

  方式一:

string url = "http://demo/api/book/";
        httpheaders headers = new httpheaders();
        mediatype type = mediatype.parsemediatype("application/json; charset=utf-8");
        headers.setcontenttype(type);
        string requestjson = "{...}";
        httpentity<string> entity = new httpentity<string>(requestjson,headers);
        string result = resttemplate.postforobject(url, entity, string.class);
        system.out.println(result);

  方式二:

@test
public void rtpostobject(){
    resttemplate resttemplate = new resttemplate();
    string url = "http://47.xxx.xxx.96/register/checkemail";
    httpheaders headers = new httpheaders();
    headers.setcontenttype(mediatype.application_form_urlencoded);
    multivaluemap<string, string> map= new linkedmultivaluemap<>();
    map.add("email", "844072586@qq.com");
 
    httpentity<multivaluemap<string, string>> request = new httpentity<>(map, headers);
    responseentity<string> response = resttemplate.postforentity( url, request , string.class );
    system.out.println(response.getbody());
}

其它:还支持上传和下载功能;

3、okhttp:okhttp是一个高效的http客户端,允许所有同一个主机地址的请求共享同一个socket连接;连接池减少请求延时;透明的gzip压缩减少响应数据的大小;缓存响应内容,避免一些完全重复的请求

当网络出现问题的时候okhttp依然坚守自己的职责,它会自动恢复一般的连接问题,如果你的服务有多个ip地址,当第一个ip请求失败时,okhttp会交替尝试你配置的其他ip,okhttp使用现代tls技术(sni, alpn)初始化新的连接,当握手失败时会回退到tls 1.0。

1)使用:它的请求/响应 api 使用构造器模式builders来设计,它支持阻塞式的同步请求和带回调的异步请求。

引入jar包:

<dependency>
    <groupid>com.squareup.okhttp3</groupid>
    <artifactid>okhttp</artifactid>
    <version>3.10.0</version>
</dependency>

2)配置文件:

import okhttp3.connectionpool;
import okhttp3.okhttpclient;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;

import javax.net.ssl.sslcontext;
import javax.net.ssl.sslsocketfactory;
import javax.net.ssl.trustmanager;
import javax.net.ssl.x509trustmanager;
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;

@configuration
public class okhttpconfiguration {

    @bean
    public okhttpclient okhttpclient() {
        return new okhttpclient.builder()
                //.sslsocketfactory(sslsocketfactory(), x509trustmanager())
                .retryonconnectionfailure(false)
                .connectionpool(pool())
                .connecttimeout(30, timeunit.seconds)
                .readtimeout(30, timeunit.seconds)
                .writetimeout(30,timeunit.seconds)
                .build();
    }

    @bean
    public x509trustmanager x509trustmanager() {
        return new x509trustmanager() {
            @override
            public void checkclienttrusted(x509certificate[] x509certificates, string s) throws certificateexception {
            }
            @override
            public void checkservertrusted(x509certificate[] x509certificates, string s) throws certificateexception {
            }
            @override
            public x509certificate[] getacceptedissuers() {
                return new x509certificate[0];
            }
        };
    }

    @bean
    public sslsocketfactory sslsocketfactory() {
        try {
            //信任任何链接
            sslcontext sslcontext = sslcontext.getinstance("tls");
            sslcontext.init(null, new trustmanager[]{x509trustmanager()}, new securerandom());
            return sslcontext.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 are subject to change in future okhttp releases. currently
     */
    @bean
    public connectionpool pool() {
        return new connectionpool(200, 5, timeunit.minutes);
    }
}

3)util工具:

import okhttp3.*;
import org.apache.commons.lang3.exception.exceptionutils;
import org.slf4j.logger;
import org.slf4j.loggerfactory;

import java.io.file;
import java.util.iterator;
import java.util.map;

public class okhttputil{
    private static final logger logger = loggerfactory.getlogger(okhttputil.class);
    
    private static okhttpclient  okhttpclient;

    @autowired
    public okhttputil(okhttpclient  okhttpclient) {
        okhttputil.okhttpclient= okhttpclient;
    } 
    
    /**
     * get
     * @param url     请求的url
     * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
     * @return
     */
    public static  string get(string url, map<string, string> queries) {
        string responsebody = "";
        stringbuffer sb = new stringbuffer(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());
                }
            }
        }
        request request = new request.builder()
                .url(sb.tostring())
                .build();
        response response = null;
        try { 
            response = okhttpclient.newcall(request).execute();
            int status = response.code();
            if (response.issuccessful()) {
                return response.body().string();
            }
        } catch (exception e) {
            logger.error("okhttp3 put error >> ex = {}", exceptionutils.getstacktrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responsebody;
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static string post(string url, map<string, string> params) {
        string responsebody = "";
        formbody.builder builder = new formbody.builder();
        //添加参数
        if (params != null && params.keyset().size() > 0) {
            for (string key : params.keyset()) {
                builder.add(key, params.get(key));
            }
        }
        request request = new request.builder()
                .url(url)
                .post(builder.build())
                .build();
        response response = null;
        try { 
            response = okhttpclient.newcall(request).execute();
            int status = response.code();
            if (response.issuccessful()) {
                return response.body().string();
            }
        } catch (exception e) {
            logger.error("okhttp3 post error >> ex = {}", exceptionutils.getstacktrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responsebody;
    }

    /**
     * get
     * @param url     请求的url
     * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
     * @return
     */
    public static string getforheader(string url, map<string, string> queries) {
        string responsebody = "";
        stringbuffer sb = new stringbuffer(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());
                }
            }
        }
        request request = new request.builder()
                .addheader("key", "value")
                .url(sb.tostring())
                .build();
        response response = null;
        try { 
            response = okhttpclient.newcall(request).execute();
            int status = response.code();
            if (response.issuccessful()) {
                return response.body().string();
            }
        } catch (exception e) {
            logger.error("okhttp3 put error >> ex = {}", exceptionutils.getstacktrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responsebody;
    }

    /**
     * post请求发送json数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一:请求url
     * 参数二:请求的json
     * 参数三:请求回调
     */
    public static string postjsonparams(string url, string jsonparams) {
        string responsebody = "";
        requestbody requestbody = requestbody.create(mediatype.parse("application/json; charset=utf-8"), jsonparams);
        request request = new request.builder()
                .url(url)
                .post(requestbody)
                .build();
        response response = null;
        try { 
            response = okhttpclient.newcall(request).execute();
            int status = response.code();
            if (response.issuccessful()) {
                return response.body().string();
            }
        } catch (exception e) {
            logger.error("okhttp3 post error >> ex = {}", exceptionutils.getstacktrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responsebody;
    }

    /**
     * post请求发送xml数据....
     * 参数一:请求url
     * 参数二:请求的xmlstring
     * 参数三:请求回调
     */
    public static string postxmlparams(string url, string xml) {
        string responsebody = "";
        requestbody requestbody = requestbody.create(mediatype.parse("application/xml; charset=utf-8"), xml);
        request request = new request.builder()
                .url(url)
                .post(requestbody)
                .build();
        response response = null;
        try { 
            response = okhttpclient.newcall(request).execute();
            int status = response.code();
            if (response.issuccessful()) {
                return response.body().string();
            }
        } catch (exception e) {
            logger.error("okhttp3 post error >> ex = {}", exceptionutils.getstacktrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responsebody;
    }
}

到此这篇关于基于springboot的resttemplate、okhttp和httpclient对比分析的文章就介绍到这了,更多相关springboot的resttemplate、okhttp和httpclient内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!