栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

RestTemplate get请求,header设置及传参方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

RestTemplate get请求,header设置及传参方式

RestTemplate get请求,header设置及传参方式

文章目录

前言

一、RestTemplate



前言

Spring Boot RestTemplate使用get请求,请求头header的设置及传参方式

1. 有参数,没有请求头
2. 有请求头,没参数
3. 有请求头,有参数


一、RestTemplate

代码如下:

package com.xinghuo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


@RestController
@Api(tags = "测试")
@RequestMapping("/test")
public class HttpController{
    
    @Autowired
    private RestTemplate restTemplate;
    
    
    @RequestMapping(value = "/http", method = RequestMethod.GET)
    @ApiOperation(value = "测试http")
    public String http() {
        String id = "52db70d13ad74b0f85142e39b32164b4";
        String name = "测试";
        //参数
        MultiValueMap param = new LinkedMultiValueMap();
        param.add("id", id);
        param.add("name", name);
        
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("accessToken", "3d40e41e9d764d30a9a4d72e61ad61b9");
        
        //封装请求头
        HttpEntity> formEntity = new HttpEntity>(headers);
        
        try {
            //访问地址
            String url = "http://localhost:8080/testservice/test/get";
            
            //1. 有参数,没有请求头,拼接方式
            String result1 = restTemplate.getForObject(url + "?id="+id+"&name="+name, String.class);
            //2. 有参数,没有请求头,占位符方式
            String result2 = restTemplate.getForObject(url + "?id={id}&name={name}", String.class, param);
            //3. 有请求头,没参数,result3.getBody()获取响应参数
            ResponseEntity result3 = restTemplate.exchange(url, HttpMethod.GET, formEntity, String.class);
            //4. 有请求头,有参数,result4.getBody()获取响应参数
            ResponseEntity result4 = restTemplate.exchange(url+"?id={id}&name={name}", HttpMethod.GET, formEntity, String.class, param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1013742.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号