springcloud下json的传递

首先服务中心要先开启,服务注册、消费注册。这里服务我使用的是eurekaclient;消费使用ribbon来做负载均衡。下面进入正题:

@Autowired
    private HelloService helloService;
    @RequestMapping(value = "/hi")
    public void hi(@RequestBody Student student){
         helloService.hi(student);
    }

这里是前端传递的json数据,没什么好说的,相信大家都能看懂

@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    public void hi(Student student)
    {
        System.out.println(student);
        HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Student> entity=new HttpEntity<Student>(student,headers);
         ResponseEntity<Student> studentResponseEntity=restTemplate.exchange("http://SERVICE-HI/hi", HttpMethod.POST,entity,Student.class);
         Student student1=studentResponseEntity.getBody();
        System.out.println(student);
    }
}

这里是重点了,利用httpHeaders来设置访问工程时的消息头,由消息头可以看出此次访问是以json形式去请求,再利用httpentity把要传递的对象和消息封装起来,用restTemplate发送请求

@RequestMapping("/hi")
	public String home(@RequestBody Student student){
		System.out.println(student);
		return "i am from port:"+port;
	}

这是服务者接受的代码,也没什么好说的,总之还是要多写多看

代码地址:https://github.com/love-dl-forever/SpringCloud

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值