如何使用 Spring RestTemplate

RestTemplate介绍使用,以及整合 HttpClient 连接池 配置长连接 1、RestTemplate介绍 spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接,我们只需要传入url及返回值类型即可。相较于之前常用的httpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。 RestTempla... 阅读详情

先简单介绍下RestTemplate的概念

RestTemplate是Spring提供的用于访问Rest服务的客户端,它提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求。

可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。
ClientHttpRequestFactory接口主要提供了两种实现方式

  • 一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接。
  • 一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息。

 RestTemplate默认是使用SimpleClientHttpRequestFactory,内部是调用jdk的HttpConnection,默认超时为-1

RestTemplate有两个构造方法,分别是:


/**
 * Create a new instance of the {@link RestTemplate} using default settings.
 */
public RestTemplate() {
    this.messageConverters.add(new ByteArrayHttpMessageConverter());
    this.messageConverters.add(new StringHttpMessageConverter());
    this.messageConverters.add(new ResourceHttpMessageConverter());
    this.messageConverters.add(new SourceHttpMessageConverter());
    this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
    if (romePresent) {
        this.messageConverters.add(new AtomFeedHttpMessageConverter());
        this.messageConverters.add(new RssChannelHttpMessageConverter());
    }
    if (jaxb2Present) {
        this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
    }
    if (jackson2Present) {
        this.messageConverters.add(new MappingJackson2HttpMessageConverter());
    }
    else if (jacksonPresent) {
        this.messageConverters.add(new MappingJacksonHttpMessageConverter());
    }
}

/**
 * Create a new instance of the {@link RestTemplate} based on the given {@link ClientHttpRequestFactory}.
 * @param requestFactory HTTP request factory to use
 * @see org.springframework.http.client.SimpleClientHttpRequestFactory
 * @see org.springframework.http.client.HttpComponentsClientHttpRequestFactory
 */
public RestTemplate(ClientHttpRequestFactory requestFactory) {
    this();
    setRequestFactory(requestFactory);
}

其中,第二个构造方法中可以传入ClientHttpRequestFactory参数,第一个进行默认初始化,因为我们经常需要对请求超时进行设置并能 够对超时进行后续处理,而第一个构造方法,我们无法控制超时时间,第二个构造中的ClientHttpRequestFactory接口的实现类中存在 timeout属性,因此选用第二个构造方法。

基于jdk的spring的RestTemplate


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd"
default-autowire="byName" default-lazy-init="true"> <!--方式一、使用jdk的实现--> <bean id="myrequestFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory"> <property name="readTimeout" value="10000"/> <property name="connectTimeout" value="5000"/> </bean> <bean id="simpleRestTemplate" class="org.springframework.web.client.RestTemplate"> <constructor-arg ref="myrequestFactory"/> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.FormHttpMessageConverter"/> <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"/> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> </beans>

 


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
 
import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
 
@Component
@Lazy(false)
public class SimpleRestClient {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleRestClient.class);
 
    private static RestTemplate restTemplate;
 
    static {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(5000);
        requestFactory.setConnectTimeout(5000);
 
        // 添加转换器
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
 
        restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(requestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
 
        LOGGER.info("SimpleRestClient初始化完成");
    }
 
    private SimpleRestClient() {
 
    }
 
    @PostConstruct
    public static RestTemplate getClient() {
        return restTemplate;
    }
 
}

 

使用Httpclient连接池的方式(推荐)


<!--使用httpclient的实现,带连接池-->
<!--在httpclient4.3版本后才有-->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">
    <property name="connectionManager">
        <bean class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
            <!--整个连接池的并发-->
            <property name="maxTotal" value="50"/>
            <!--每个主机的并发-->
            <property name="defaultMaxPerRoute" value="50"/>
        </bean>
    </property>
    <!--开启重试-->
    <property name="retryHandler">
        <bean class="org.apache.http.impl.client.DefaultHttpRequestRetryHandler">
            <constructor-arg value="2"/>
            <constructor-arg value="true"/>
        </bean>
    </property>
    <property name="defaultHeaders">
        <list>
            <bean class="org.apache.http.message.BasicHeader">
                <constructor-arg value="Content-Type"/>
                <constructor-arg value="text/html;charset=UTF-8"/>
            </bean>
            <bean class="org.apache.http.message.BasicHeader">
                <constructor-arg value="Accept-Encoding"/>
                <constructor-arg value="gzip,deflate"/>
            </bean>
            <bean class="org.apache.http.message.BasicHeader">
                <constructor-arg value="Accept-Language"/>
                <constructor-arg value="zh-CN"/>
            </bean>
        </list>
    </property>
</bean>

<bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build"/>

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <property name="messageConverters">
        <list value-type="org.springframework.http.converter.HttpMessageConverter">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <value>text/html;charset=UTF-8</value>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <value>application/json;charset=UTF-8</value>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"/>
        </list>
    </property>
    <property name="requestFactory">
        <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
            <constructor-arg ref="httpClient"/>
            <!--连接时间(毫秒)-->
            <property name="connectTimeout" value="20000"/>
            <!--读取时间(毫秒)-->
            <property name="readTimeout" value="20000"/>
        </bean>
    </property>
</bean>

 


import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
 
import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
 
@Component
@Lazy(false)
public class RestClient {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleRestClient.class);
 
    private static RestTemplate restTemplate;
 
    static {
        // 长连接保持30秒
        PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
        // 总连接数
        pollingConnectionManager.setMaxTotal(1000);
        // 同路由的并发数
        pollingConnectionManager.setDefaultMaxPerRoute(1000);
 
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setConnectionManager(pollingConnectionManager);
        // 重试次数,默认是3次,没有开启
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
        // 保持长连接配置,需要在头添加Keep-Alive
        httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
 
//        RequestConfig.Builder builder = RequestConfig.custom();
//        builder.setConnectionRequestTimeout(200);
//        builder.setConnectTimeout(5000);
//        builder.setSocketTimeout(5000);
//
//        RequestConfig requestConfig = builder.build();
//        httpClientBuilder.setDefaultRequestConfig(requestConfig);
 
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
        headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
        headers.add(new BasicHeader("Accept-Language", "zh-CN"));
        headers.add(new BasicHeader("Connection", "Keep-Alive"));
 
        httpClientBuilder.setDefaultHeaders(headers);
 
        HttpClient httpClient = httpClientBuilder.build();
 
        // httpClient连接配置,底层是配置RequestConfig
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        // 连接超时
        clientHttpRequestFactory.setConnectTimeout(5000);
        // 数据读取超时时间,即SocketTimeout
        clientHttpRequestFactory.setReadTimeout(5000);
        // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
        clientHttpRequestFactory.setConnectionRequestTimeout(200);
        // 缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。
        // clientHttpRequestFactory.setBufferRequestBody(false);
 
        // 添加内容转换器
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
 
        restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
 
        LOGGER.info("RestClient初始化完成");
    }
 
    private RestClient() {
 
    }
 
    @PostConstruct
    public static RestTemplate getClient() {
        return restTemplate;
    }
 
}

Spring的RestTemplate对post的常用接口:

public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables)
            throws RestClientException
public <T> T postForObject(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables)
            throws RestClientException
public <T> T postForObject(URI url, Object request, Class<T> responseType) throws RestClientException

rest POST 使用例子


HttpHeaders headers = new HttpHeaders();
headers.add("X-Auth-Token", "e348bc22-5efa-4299-9142-529f07a18ac9");

MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("owner", "11");
postParameters.add("subdomain", "aoa");
postParameters.add("comment", "");

HttpEntity<MultiValueMap<String, String>> requestEntity  = new HttpEntity<MultiValueMap<String, String>>(postParameters, headers);

ParseResultVo exchange = null;
try {
    exchange = restTemplate.postForObject("http://l-dnsutil1.ops.beta.cn6.qunar.com:10085/v1/cnames/tts.piao",  requestEntity, ParseResultVo.class);
    logger.info(exchange.toString());
} catch (RestClientException e) {
    logger.info("。。。。");
}


package com.winner.rest;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;


@Service
public class TestGet {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 要请求的url,一般放在配置文件中
     */
    @Value(value = "@{remote.url}")
    private String remoteUrl;

    public String postRemoteData(ParameterRo ro) throws UnsupportedEncodingException {
        /**
         * 设置请求头
         */
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        /**
         * POST请求参数,根据需要进行封装
         */
        String bodyData = new String(Base64Util.encodeData(JSON.toJSONString(ro)).getBytes("UTF-8"), "UTF-8");

        /**
         * 查看HttpEntity的构造方法,包含只有请求头和只有请求体的情况
         */
        HttpEntity<String> httpEntity = new HttpEntity<String>(bodyData, headers);

        /**
         * 执行操作
         */
        String result = restTemplate.postForObject(remoteUrl, httpEntity, String.class);

        return result;
    }

    /**
     * 模拟请求参数
     */
    private class ParameterRo {
        
        private Integer id = 123;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }
    }
}


Spring的RestTemplate提供了许多的 rest GET 方法支持,这里仅仅列出常用的rest GET接口:

public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) throws RestClientException 
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> urlVariables) throws RestClientException
public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException

对于GET请求来说,常用的几种形式如下:

String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class,"42", "21");

或者下面这种形式:

Map<String, String> vars = Collections.singletonMap("hotel", "42");
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{hotel}", String.class, vars);

以及:

String message = restTemplate.getForObject("http://localhost:8080/yongbarservice/appstore/appgoods/restTemplate?name=zhaoshijie&id=80", String.class );

package com.winner.rest;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;


@Service
public class TestGet {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 要请求的url,一般放在配置文件中
     */
    @Value(value = "@{remote.url}")
    private String remoteUrl;

    public String getRemoteData(ParameterRo ro) throws UnsupportedEncodingException {

        //根据需要也可以设置请求头

        /**
         * get请求参数,根据需要进行封装(加密等)
         */
        String getData = new String(Base64Util.encodeData(JSON.toJSONString(ro)).getBytes("UTF-8"), "UTF-8");

        /**
         * 执行操作
         */
        String result = restTemplate.getForObject(remoteUrl + "?" + getData, String.class);

        return result;
    }

    /**
     * 模拟请求参数
     */
    private class ParameterRo {

        private Integer id = 123;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }
    }
}
Java内部利用RestTemplate发送Http请求 阅读详情

相关推荐

Spring boot注入RestTemplate实例的2种方式

RestTemplate是我们使用的比较多的模板,用来发送http请求。大多数情况下,需要我们自己注入到Spring IOC容器。 对于低版本的spring boot,比如spring boot 1.3.7,是不支持RestTemplateBuilder创建RestTemplate实例的。 怎么办呢,如下: @Bean public RestTemplate restTemplate() { return new RestTemplate(); } 如果是spring boo...

reggergdsg的博客 5518

RestTemplate组件:ClientHttpRequestFactory、ClientHttpRequestInterceptor、ResponseExtractor【享学Spring MVC】

前言 本文为深入了解Spring提供的Rest调用客户端RestTemplate做准备,对和它相关的周边类做一个打点。 因为单词相似,请注意区分RestTemplate和RedisTemplate哦~ ClientHttpRequestFactory 它是个函数式接口,用于根据URI和HttpMethod创建出一个ClientHttpRequest来~ 说明:ClientHttpRequest...

架构师:通透,才能写出好代码! 4万+

从零到一:Ubuntu22.04下VSCode与中文输入法的深度整合指南

本文详细介绍了在Ubuntu22.04系统中如何深度整合VSCode与中文输入法,包括环境准备、安装方案对比、输入法配置及常见问题解决方案。通过fcitx框架优化中文输入体验,提供从基础设置到高级调试的全方位指南,帮助开发者提升在Linux环境下的开发效率。

weixin_29158047的博客 477

【Spring】RestTemplate 浅析

一直在使用RestTemplate 进行服务之间API的调用,只知道RestTemplate restTemplate=new RestTemplate(),然后就可以直接使用post或者get等方法进行请求;直到最近遇到一个问题,在服务之间进行大文件的传输时,总是报出内存溢出的问题,才意识到学习不能浅尝辄止,要明白其中的原理才能够遇到问题时随机应变。本篇文章只是对RestTemplate的源码的一个浅析,不足之处还望读者多包涵。 1、RestTemplate基础     RestTemplate是Sp.

qgnczmnmn的博客 2446

DPO(Direct Preference Optimization)直接偏好优化

本文介绍了DPO(直接偏好优化)方法,该方法通过简化传统的RLHF(基于人类反馈的强化学习)流程,直接利用人类偏好数据进行模型优化。DPO的核心思想是跳过奖励模型训练和强化学习交互步骤,通过数学推导将优化目标转化为仅与策略概率分布相关的形式。推导表明最优策略与奖励模型之间存在显式关系,从而可以构建直接优化策略的损失函数。与RLHF相比,DPO简化了训练流程,提高了工程实现稳定性,同时保持了同等效果。

TeenLucifer的博客 1954

FreeCAD MCP实战:用AI自然语言驱动CAD建模与自动化

在计算机辅助设计(CAD)领域,参数化建模和自动化脚本是提升设计效率的核心技术。其原理在于通过程序化指令控制三维模型的创建与修改,从而将设计意图转化为精确的几何实体。这种技术价值在于显著降低重复性操作成本,实现快速原型迭代和设计探索。在应用场景上,它尤其适用于需要频繁调整尺寸、生成系列化零件或执行规则化建模任务的工程与产品设计。本文聚焦的FreeCAD MCP项目,正是这一理念的先进实践。它通过集成Model Context Protocol(MCP),构建了一个连接Claude AI与FreeCAD的智能

weixin_26913055的博客 723

RestTemplate使用HttpClient连接池

为什么要用连接池? 因为使用它可以有效降低延迟和系统开销。如果不采用连接池,每当我们发起http请求时,都需要重新发起Tcp三次握手建立链接,请求结束时还需要四次挥手释放链接。而Tcp链接的建立和释放是有时间和系统开销的。另外每次发起请求时,需要分配一个端口号,请求完毕后在进行回收。使用链接池则可以复用已经建立好的链接,一定程度的避免了建立和释放链接的时间开销。

C. 4907

UEFI 基础教程 (零) - 目录

UEFI 基础教程 (十八) — UEFI Build Process简单分析。UEFI 基础教程 (十五) — 获取UEFI MemoryMap。UEFI 基础教程 (六)   —  PROTOCOL 简单使用。UEFI 基础教程 (十)   —  FileIO 简单使用。UEFI 基础教程 (一)   —  搭建UEFI开发环境。UEFI 基础教程 (九)   —  EVENT 简单使用。UEFI 基础教程 (七)   —  HOB 简单使用。UEFI 基础教程 (八)   —  PCD 简单使用。..

技术联盟 1536

Spring之RestTemplate详解

文章目录1 RestTemplate1.1 引言1.2 环境配置1.2.1 非Spring环境下使用RestTemplate1.2.2 Spring 环境下使用 RestTemplate1.3 API 实践1.3.1 GET请求1.3.1.1 不带参请求1.3.1.2 带参的get请求(使用占位符号传参)1.3.1.3 带参的get请求(restful风格)1.3.1.4 getForEntity使用示例1.3.2 POST请求1.3.2.1 模拟表单请求1.3.2.2 模拟表单请求(传递对象)1.3.2.

上善若泪 3万+

华为OD机试真题 C 实现【水库蓄水问题】【2022.11 Q4 新题】

给定一个长度为 n 的整数数组height。数组的元素表示山的高度,选择两个元素作为水库的边界,求蓄水量的最大值并输出蓄水量最大时的边界下标(蓄水量相同时输出下标较近的)。

MISAYAONE的博客 1万+

微信小程序 - 最新获取用户昵称 / 头像(wx.getUserProfile 接口被废弃后的代替方案)详细教程,2022 年之后的所有微信小程序,获取用户信息最新详细教程,附带示例源代码

微信小程序wx.getUserProfile接口废了用什么代替,微信小程序wx.getUserProfile不能用了怎么办,wx.getUserProfile失效有什么替代方案吗,微信新规定头像昵称填写最新教程,目前微信小程序最新获取用户头像昵称教程,微信小程序用户头像昵称获取规则调整公告,2022改版后的微信小程序如何获取用户头像和昵称信息,微信小程序官方废弃getUserProfile后如何实现获取用户信息,微信小程序wx.getUserProfile接口返回了默认头像昵称,微信小程序获取用户信息不

🏆 前端领域优质创作者 2万+

Spring Boot教程之十二: Spring – RestTemplate

要与 REST 交互,客户端需要创建客户端实例和请求对象、执行请求、解释响应、将响应映射到域对象以及处理异常。发送 HTTP GET 请求,返回包含从响应主体映射的对象的 ResponseEntity。将数据 POST 到 URL,返回包含从响应主体映射的对象的 ResponseEntity。对 URL 执行指定的 HTTP 方法,返回包含对象的 ResponseEntity。针对 URL 执行指定的 HTTP 方法,返回从响应主体映射的对象。发送 HTTP GET 请求,返回从响应主体映射的对象。

潜洋的专栏 2845

13、HTML 表格创建与样式设置全攻略

本文全面介绍了HTML表格的创建与样式设置方法,涵盖表格行列添加、边框控制、行和列分组(thead、tbody、tfoot、colgroup)、宽度与高度设置、内边距与间距调整,以及表格对齐方式。同时提供了最佳实践建议、常见问题解决方案及综合示例代码,帮助开发者构建结构清晰、样式美观且兼容性强的HTML表格。

blue的专栏 97

关于Spring的RestTemplate的使用

关于Spring的RestTemplate的使用1 RestTemplate的简介2 RestTemplate的使用consumer-a服务provider-a服务测试功能使用过程中遇到的问题 现在微服务项目中, 各个服务之间的互相请求调用, 越来越频繁, 所以出现了很多Http请求工具, 而Spring提供的 RestTemplate,则是比较友好的封装集成了一些常见的Http请求工具,可以根据不同的使用场景,灵活的切换 1 RestTemplate的简介 RestTemplate是Spring3.0

ABestRookie的博客 1476

《UDS协议从入门到精通》系列——图解0x85:控制DTC的设置

如何让ECU停止或恢复DTC状态位更新?有哪些注意点?图解+示例教你快速上手UDS 0x85服务!!

车载系统攻城狮 3861

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Spring RestTemplate配置及使用

配置 // 配置类 @Configuration public class RestTemplateConfiguration { @Bean public RestTemplate restTemplate(){ RestTemplate restTemplate = new RestTemplate(); // 设置字符串转换器编码 restTemplate.getMessageConverters().set(1, new StringH

qq_16608213的博客 1668

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

spring的RestTemplate使用指南

前言:现在restful接口越来越广泛,而如今很多接口摒弃了传统的配置复杂的webService开发模式,在java领域只需要很简单的springMvc就可以声明为一个控制器,再加上service层,就可以直接操作数据库成为一个灵活的接口。而我们请求接口的次数也会越来越多(最近我在和一个工具对接的时候,对方公司提供的接口全部由我们主动去调用),一般我们请求接口,都采用Apache Httpclient工具,这个工具稳定,既可以建立长连接,保持不错的性能,而它唯一的不足就是使用起来麻烦多变,并且要很多层判断处

weixin_42650954的博客 1020

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

spring之RestTemplate

文章目录一、RestTemplate 语法二、配置类的使用步骤一:编写配置类,将需要new的对象交于spring进行管理步骤二:在任意位置,通过@Resource进行注入创建 RestTemplate一些其他设置1. 拦截器配置2. ErrorHandler 配置3. HttpMessageConverter 配置4.路由配置 RestTemplate是spring的一个rest客户端,在spring-web这个包下,spring boot的依赖如下 <dependency> &lt

Mr.Debug的博客 2026

spring RestTemplate使用

最近看到spring RestTemplate,觉得挺好用的,就研究总结了一下,第一次写。。。 RestTemplate可使用http的所有方式进行请求,本文主要说明下get,post的使用,其他的基本类似。http get 方式spring RestTemplate中直接使用get方法有两种getForObject和getForEntitygetForObject每种方式都有3个重载方法 T g

LV003的专栏 8000

Spring Cloud 服务调用 RestTemplate

是 Spring 提供的同步 HTTP 客户端工具,封装了与 RESTful 服务交互的常用操作,支持发送 GET、POST、PUT、DELETE 等请求,同时提供序列化和反序列化功能,使开发者能够轻松完成与远程服务的通信。在 Spring Cloud 微服务架构中,RestTemplate 通常与负载均衡器(如 Ribbon)结合使用,帮助服务消费者从服务注册中心(如 Eureka)获取服务实例并实现自动负载均衡。

Flying_Fish_roe的博客 1597

Spring RestTemplate 使用拦截器

Spring RestTemplate 经常被用作客户端向 Restful API发送各种请求,在开发过程中我们会发现很多请求都会有相同的场景,如请求携带认证的token、验证的签名、打印请求和响应日志等。在请求方法里面添加这些通用的非业务逻辑,代码显得很冗余。这个时候我们就思考,我们是不是就可以将这些非业务性代码抽取出来进行复用。Spring 提供了 ClientHttpRequestInterceptor 接口,可以对请求进行拦截,并在其被发送至服务端之前修改请求或是增强相应的信息。

javaTalk 3548

spring中restTemplate的使用

新建restTemplate实例可以直接new也可以使用springboot提供的RestTemplateBuilder。 @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } restTemplate有很多的方法,postForObject,postForEntity等,这些是直接调用的,如: Coffee coffee = restTemplate.postFor

TY_zhong的博客 949

Spring中RestTemplate详解

1.概述 RestTemplate是spring封装的restful请求的模板,它内部封装了常用的GET、POST、DELETE、PUT等请求方式,帮助开发者更快构建HTTP请求。传统的请求方式采用Apache的HttpClient,此种方式编写http请求时需要编写大量代码,比较繁琐。本文将从代码量、以及最大访问量对比HttpClient与Restemplate请求封装的工具类。 2.基于HttpClient封装的工具类 2.1 GET请求 2.2 POST请求 2.3 DELETE请求 2.4 PUT请

qq_33479841的博客 9310

spring的restTemplate使用

本文只列出了,get请求与post的请求的使用,至于其他的,put,delete请求,与get和post请求的方式都相差不多,我将这个RestTemplate的例子传到了网盘上,大家如果有兴趣可以下载研究。链接: https://pan.baidu.com/s/1yidh07u5I6MF_yLkls1ycA?pwd=gkg5 提取码: gkg5 复制这段内容后打开百度网盘手机App,操作更方便哦。

郝老三~~~~~~~~~~~~~ 1626

Spring’s RestTemplate

Spring’s RestTemplate /** * After the word document is generated in memory we can upload it to the server. * * @param fileContents The byte array we're wanting to POST * @param filename ...

weixin_30827565的博客 97
上一篇: 分布式消息系统kafka
下一篇: JSch Java实现的 SFTP功能的利器
大树叶
博客等级 码龄12年 1171粉丝 664原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值