0827RestTempalte接口设置

package com.example.demo.service.lmpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.service.TokenService;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@Service
public class TokenServiceImpl implements TokenService {
    public String formData(){
        String url = "Token网址";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        //接口参数(设置body,form-data)
        map.add("test_type","test_credentials");
        map.add("client_id","1234567");
        map.add("client_secret","1234567890");
        //头部类型(设置请求头部类型FORM_DATA)
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //构造实体对象
        HttpEntity<MultiValueMap<String, String>> param = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        //发起请求,服务地址,请求参数,返回消息体的数据类型
        ResponseEntity<String> response = restTemplate.postForEntity(url, param, String.class);
        //body
        String strBody = response.getBody();
        JSONObject jsonobj = JSON.parseObject(strBody);

        String ss = jsonobj.getString("access_token");
        //JSON格式转为Map类型
        Map result = JSON.parseObject(strBody, Map.class);
        return ss;
    }
    public String RealTimeData(){
        RestTemplate template = new RestTemplate();
        String Token = formData();

        String url = "接口网址";

        Map body = new HashMap();
        body.put("vin","123testtttt");
        //设置body数据类型
        String bodyData = JSON.toJSONString(body);
        HttpHeaders headers = new HttpHeaders();
        //请求头部,设置Authorization为Bearer 类型,和相应的Token
        headers.add("Authorization", "Bearer "+Token);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(bodyData,headers);
        ResponseEntity<String> response = template.exchange(url, HttpMethod.POST, entity, String.class);
        String strbody = response.getBody();
//        System.out.println(response.getBody());
        return strbody;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值