设置pom引用

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.itstudy</groupId>
<artifactId>demo</artifactId>
<version>1.0.0-SNAPSHOT</version> <name>demo</name> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.30</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

2.增加配置类

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;
import org.springframework.http.converter.StringHttpMessageConverter;
import java.nio.charset.Charset; @Configuration
public class RestTemplateConfig { @Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
RestTemplate restTemplate= new RestTemplate(factory);
// 支持中文编码
restTemplate.getMessageConverters().set(1,
new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate; } @Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//单位为ms
factory.setConnectTimeout(5000);//单位为ms
return factory;
}
}

3.在service中使用

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate; public class RestTestService { @Autowired
private RestTemplate restTemplate; public void test(){ String paras = "data";
String url="http://127.0.0.1"; HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
JSONObject jsonObj = JSONObject.parseObject(paras);
HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
String result = restTemplate.postForObject(url, formEntity, String.class);
} public void testExchage(){ String url=""; HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); Map<String,String> postData = new HashMap<String,String>();
postData.put("param1","");
postData.put("param2","abc"); //发送json字符串
String content = JSON.toJSONString(postData); HttpEntity<String> httpEntity = new HttpEntity<String>(content, httpHeaders); try { ResponseEntity<String> responseEntity =
restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); Map<String,String> mapResponse = JSON.parseObject(responseEntity.getBody(),HashMap.class); }catch (Exception ex){
//进行错误处理
}
} public void testExchage2(){ String url=""; HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); //参数放入一个map中,restTemplate不能用hashMap
MultiValueMap<String,String> param = new LinkedMultiValueMap<String, String>();
//将请求参数放入map中
param.add("param1","abc");
param.add("param2",""); //将参数和header组成一个请求
HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<MultiValueMap<String,String>>(param,headers); try {
ResponseEntity<String> responseEntity =
restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); //responseEntity.getBody()进行其它处理 }catch (Exception ex){
//进行错误处理
}
}
}

4.应用启动

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication app = new SpringApplication(App.class);
//关闭banner
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
} }

另外注意RestTemplate默认 如果返回状态不是200则会报错,因此这个要进行捕获

/判断接口返回是否为200
public static Boolean ping(){
String url = domain + "/it/ping";
try{
ResponseEntity<String> responseEntity = template.getForEntity(url,String.class);
HttpStatus status = responseEntity.getStatusCode();//获取返回状态
return status.is2xxSuccessful();//判断状态码是否为2开头的
}catch(Exception e){
return false; //502 ,500是不能正常返回结果的,需要catch住,返回一个false
}
}

或者进行自定义处理

import java.io.IOException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate; @Configuration
public class RestTemplateConfig {
    
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) throws Exception {
        RestTemplate restTemplate = new RestTemplate(factory);
        ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
                return true;
            }
            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {             }
        };
        restTemplate.setErrorHandler(responseErrorHandler);
        return restTemplate;
    }
    
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //读取超时5秒
        factory.setReadTimeout();
        //连接超时15秒
        factory.setConnectTimeout();
        return factory;
    }
}

SpringBoot使用RestTemplate的更多相关文章

  1. SpringBoot系列: RestTemplate 快速入门

    ====================================相关的文章====================================SpringBoot系列: 与Spring R ...

  2. SpringBoot 使用 RestTemplate 调用exchange方法 显示错误信息

    SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...

  3. SpringBoot使用RestTemplate基础认证

    SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...

  4. SpringBoot使用RestTemplate 摘要认证

    SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...

  5. Springboot 使用 RestTemplate

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code spring web 项目提供的RestTemplate,使java访问url更方便, ...

  6. SpringBoot配置RestTemplate的代理和超时时间

    application.properties: #代理设置 proxy.enabled=false proxy.host=192.168.18.233 proxy.port=8888 #REST超时配 ...

  7. springboot使用RestTemplate以post方式发送json字符串参数(以向钉钉机器人发送消息为例)

    使用springboot之前,我们发送http消息是这么实现的 我们用了一个过时的类,虽然感觉有些不爽,但是出于一些原因,一直也没有做处理,最近公司项目框架改为了springboot,springbo ...

  8. SpringBoot集成RestTemplate

    先把原文列出来: springboot实战之常用http客户端整合 springboot2.0集成RestTemplate -----------开始------------ SpringBoot应用 ...

  9. springboot系列十二、springboot集成RestTemplate及常见用法

    一.背景介绍 在微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端.我们可以使用JDK原生的URLConnection.Apache的Http Client.N ...

随机推荐

  1. c调用c++

    g++ main.c math.cpp math.h中加入extern "C"

  2. Markdown的使用和计算机基础

    TOC] 一级标题 这不是开玩笑 你问我为什么? 粗的才好(滑稽) 什么!明明有人推我 ==一闪一闪亮晶晶== 我上面有人^人在这^ water?H~2~O(下标) hello world! hell ...

  3. java:Conllection(List,set,get,map,subList)使用

    list中的contains:是否包含指定元素 list中的SubList:  返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图. List<String ...

  4. Arduino库

    单总线库: 下载地址  :  链接:https://pan.baidu.com/s/1YSuqrXWuBAxMEUWHy8rckw    提取码:svix 把整个文件夹复制到 Arduino安装目录的 ...

  5. CSS3——PC以及移动端页面适配方法(流体布局)

    流体布局:使用百分比来设置元素的宽度,元素的高度按照实际值. 但是流体布局中存在一个边框的问题,元素的边线无法计入百分比. 两种解决办法: 1)width:calc(20% - 4px) 2)widt ...

  6. 3D世界变换

    一直弄不清3D场景中scaleOrientation的作用,还有scale.orientation(roation).translation的顺序问题,以往都是试图查一下,关于前者网上几乎找不到什么清 ...

  7. CSS颜色和长度单位

    颜色 如果我们相给页面设置颜色可以采用多种方法进行设置: 一.命名颜色 假设在设置页面的颜色时觉得一部分很小的颜色集中就足够了,就可以直接给定颜色的名称.CSS称这些有名称的颜色为命名颜色. 命名颜色 ...

  8. 设计模式学习笔记——Adapter 适配器模式

    适配器设计模式的适应场景: 一般情况是上端固定,下端固定,下端功能不满足或跟上端不协调,使用适配器重新包一层(继承适配器接口,以满足上端需求,继承下层类,以调用方法),使下端代码能满足上端需求(欺骗, ...

  9. 5 November

    拓扑排序 for (int i=1; i<=n; ++i) if (!ind[i]) q.push(i); while (!q.empty()) { int now=q.top(); q.pop ...

  10. SQL 批量修改一个字段的值为另一个字段的值

    AND create_time BETWEEN '2016-07-25 14:30:00' AND '2016-07-25 15:20:28'; AND create_time BETWEEN '20 ...