java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring-boot oauth2 后台自动登录

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

作者:Guoye

这篇文章主要介绍了Spring-boot oauth2使用RestTemplate进行后台自动登录的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

内容不限于登录业务,主要简单介绍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);

 到此这篇关于Spring-boot oauth2使用RestTemplate进行后台自动登录的实现的文章就介绍到这了,更多相关Spring-boot oauth2 后台自动登录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文