转载

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

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

postForObject
MultiValueMap
JSONObject
HttpHeaders

登录流程

  • 定义 RestTemplate
  • 定义 MultiValueMap,构造 post的body内容
  • 定义 HttpHeaders,构造请求的头部信息
  • 定义 HttpEntity,发送请求的实体
  • 定义 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);
原文  https://segmentfault.com/a/1190000023077078
正文到此结束
Loading...