restTemplate的post方法传递参数

1.问题背景

服务之间调用,通过spring自带的restTemplate访问nacos网关服务,   网关路由到真正需要的服务上  ,此过程需要携带对象参数及token

package com.zy;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;


/**
 * @author zy
 * @Classname ComsumerApplication
 * @Description TODO
 * @Date 2020/12/23 17:03
 */
@SpringBootApplication(scanBasePackages = "com.zy")
public class ComsumerApplication implements CommandLineRunner {

    @NacosInjected
    private NamingService namingService;

    public static void main(String[] args) {
        SpringApplication.run(ComsumerApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        // 根据服务名从注册中心获取一个健康的网关服务实例
        Instance instance = namingService.selectOneHealthyInstance("gateway");


       //创建header对象,携带token
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjhjZjhlZmNlLTJiYTgtNGY5My04ODNkLTNlNGQxOWFlMzg2MSJ9.tBOqkIWzMhZWvu7uI4jrQcENiBL54DMF9CrsyjVvcSpW58DbMHTLr-rGmhd7MnNOZHc3x9C_2Ll_2Gs_M0trlA");
        //设置文本类型为json格式
        headers.add("Content-Type", "application/json");

        //创建json对象
        JSONObject para = new JSONObject();
        para.put("page", "1");
        para.put("size", "1");
        para.put("taskName", "");
        //创建模板                       
        RestTemplate template = new RestTemplate();
        
        //创建携带参数实体类
        HttpEntity<String> formEntity = new HttpEntity<String>(para.toJSONString(), headers);
        String url = String.format("http://%s:%d/gatherTask/fuzzySearch", instance.getIp(), instance.getPort());
        //这里通过exchange访问  兼容post get put delete等方式
        ResponseEntity<String> response = template.exchange(
                url,//获取资源的地址
                HttpMethod.POST,
                formEntity,
                String.class//返回类型设为String
        );
        String body = response.getBody();
        System.out.println(body);

    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值