Springboot 使用 RestTemplate

每天学习一点点 编程PDF电子书、视频教程免费下载:
http://www.shitanlife.com/code

 

 

spring web 项目提供的RestTemplate,使java访问url更方便,更优雅。

它是spring提供的异步的客户端http访问的核心class,它提供非常简单的RESTful方式与http server端进行数据交互,根据所提动的URLs进行http访问,并处理返回结果。它是基于JDK HTTP connection建立的。因此他可以使用不同的HTTP库(apache,netty and OkHttp)来setRequestFactory。

它实现了以下6个主要的HTTP meshod:

HTTP methodRestTemplate methods
DELETE delete
GET getForObject,getForEntity
HEAD headForHeaders
OPTIONS optionsForAllow
PUT put
any exchange,execute

现简单介绍在Springboot中使用RestTemplate

首先在代码中加入RestTemplate的配置类

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;

/**
 * Created by liuxu on 2017/12/22.
 * RestTemplate配置类
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }
}

 

然后在需要访问url的类中注入RestTemplate

@Autowired
private RestTemplate restTemplate;

使用RestTemplate发送get请求

//get json数据
JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();

 

使用RestTemplate发送post请求

//post json数据
JSONObject postData = new JSONObject();
postData.put("data", "request for post");
JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();

//对基本类型的解析 JSONObject obj =
json ;
System.out.println("name:" + obj.getString("name")); 
System.out.println("sex:" + obj.getString("sex"));
System.out.println("age" + obj.getInt("age"));
System.out.println("is_student" + obj.getBoolean("is_student"));
//对数组的解析
JSONArray hobbies = obj.getJSONArray("hobbies");
System.out.println("hobbies:");
for (int i = 0; i < hobbies.length(); i++) { String s = (String) hobbies.get(i); System.out.println(s); }

设置请求头

//post json string data
//return string
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);

 

 

 

 

每天学习一点点 编程PDF电子书、视频教程免费下载:
http://www.shitanlife.com/code

posted @ 2018-04-10 09:15  漫步CODE人生  阅读(1115)  评论(0编辑  收藏  举报