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; } }
0827RestTempalte接口设置
最新推荐文章于 2024-09-27 00:45:01 发布