Spring-boot oauth2使用RestTemplate进行后台自动登录的实现
内容不限于登录业务,主要简单介绍RestTemplate的用法,包括
- 使用RestTemplate进行post请求postForObject
- 使用RestTemplate带body/form-data进行post请求MultiValueMap
- 使用RestTemplate带josn进行post请求JSONObject
- 使用RestTemplate带头信息headers进行post请求HttpHeaders
登录流程
- 定义RestTemplate
- 定义MultiValueMap,构造post的body内容
- 定义HttpHeaders,构造请求的头部信息
- 定义HttpEntity,发送请求的实体
- 定义RestTemplate,进行请求。返回数据
主要代码
//构造post的body内容(要post的内容,按需定义) MultiValueMapparamsMap=newLinkedMultiValueMap<>(); paramsMap.set("grant_type","password"); paramsMap.set("username","yourname"); paramsMap.set("password","yourpassword"); //构造头部信息(若有需要) HttpHeadersheaders=newHttpHeaders(); headers.add("Authorization","Basicxxxxxx你的认证密钥"); //设置类型"application/json;charset=UTF-8" headers.setContentType(MediaType.APPLICATION_JSON); //构造请求的实体。包含body和headers的内容 HttpEntity >request=newHttpEntity(paramsMap,headers); //声明restTemplateAuth(用作请求) RestTemplaterestTemplateAuth=newRestTemplate(); //进行请求,并返回数据 StringauthInfo=restTemplateAuth.postForObject("http://localhost:8089/oauth/token",request,String.class);
使用josn请求的示例代码
PostingJSONwithpostForObject JSONObjectpersonJsonObject=newJSONObject(); personJsonObject.put("id",1); personJsonObject.put("name","John"); HttpEntityrequest=newHttpEntity (personJsonObject.toString(),headers); StringpersonResultAsJsonStr=restTemplate.postForObject("url",request,String.class);
到此这篇关于Spring-bootoauth2使用RestTemplate进行后台自动登录的实现的文章就介绍到这了,更多相关Spring-bootoauth2后台自动登录内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!