当前位置:主页 > 软件编程 > JAVA代码 >

Spring-boot oauth2使用RestTemplate进行后台自动登录的实现

时间:2021-06-19 08:18:53 | 栏目:JAVA代码 | 点击:

内容不限于登录业务,主要简单介绍RestTemplate的用法,包括

登录流程

主要代码

  // 构造 post的body内容(要post的内容,按需定义)
  MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
  paramsMap.set("grant_type", "password");
  paramsMap.set("username", "yourname");
  paramsMap.set("password", "yourpassword");

  // 构造头部信息(若有需要)
  HttpHeaders headers = new HttpHeaders();
  headers.add("Authorization", "Basic xxxxxx你的认证密钥");
  // 设置类型 "application/json;charset=UTF-8"
  headers.setContentType(MediaType.APPLICATION_JSON); 
  
  // 构造请求的实体。包含body和headers的内容
  HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(paramsMap, headers);
  
  // 声明 restTemplateAuth(用作请求)
  RestTemplate restTemplateAuth = new RestTemplate(); 
  // 进行请求,并返回数据 
  String authInfo = restTemplateAuth.postForObject("http://localhost:8089/oauth/token", request, String.class);

使用josn请求的示例代码

Posting JSON with postForObject

  JSONObject personJsonObject = new JSONObject();
  personJsonObject.put("id", 1);
  personJsonObject.put("name", "John");

  HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
  String personResultAsJsonStr = restTemplate.postForObject("url", request, String.class);

您可能感兴趣的文章:

相关文章