SpringBoot使用RestTemplate进行Basic auth接口调用
(推荐)方式一:使用RestTemplateBuilder自动配置
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Autowired
private RestTemplateBuilder restTemplateBuilder;
@Bean
public RestTemplate restTemplate(){
return restTemplateBuilder.basicAuthorization("admin","admin").build();
}
}
@RestController
public class Test {
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value = "/test")
private String getRestResponse() {
String url ="http://192.168.17.8:6080/service/public/v2/api/service/1";
try {
return restTemplate.getForObject(url, String.class);
} catch(Exception ex) {
return ex.toString();
}
}
方式二:
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class TestRanger {
private static final String EXPECTED_MIME_TYPE = "application/json";
static String rangerBaseUrl = "http://192.168.17.8:6080";
public static void getPolicyByName() {
String url = rangerBaseUrl + "/service/public/v2/api/service/1";
String plainCreds = "admin:admin";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
headers.add("Content-Type","application/json");
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
String str = response.getBody();
System.out.println(str);
}
public static void main(String[] args) {
getPolicyByName();
}
}
方式二实际应用
package com.xxxxx.indirect.manage.service.impl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxxxx.indirect.manage.service.SsoLinkForNewService;
import com.xxxxx.indirect.manage.threeapi.oa.vo.SsoRquestVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;
@Service
@Slf4j
public class SsoLinkForNewServiceImpl implements SsoLinkForNewService {
/**
* api地址
*/
@Value("${three.oa.new.apiUrl}")
private String apiUrl;
/**
* appid
*/
@Value("${three.oa.new.appId}")
private String appId;
/**
* basic auth认证的用户名
*/
@Value("${three.oa.new.username}")
private String username;
/**
* basic auth认证的密码
*/
@Value("${three.oa.new.password}")
private String password;
/**
* 新的接口-根据工号获取流程SSOUrl
* @param ssoRquestVO
* @return
*/
@Override
public String getLinkForNew(SsoRquestVO ssoRquestVO) {
//创建basic auth认证的入参
String plainCreds = username+":"+password;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64Utils.encode(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
//使用restTemplate调接口
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
headers.add("Content-Type","application/json");
headers.add("appid",appId);
HttpEntity<SsoRquestVO> entity = new HttpEntity<SsoRquestVO>(ssoRquestVO,headers);
ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);
// 处理响应
if (response.getStatusCode().is2xxSuccessful()) {
String responseBody = response.getBody();
String s = parseResponse(responseBody);
return s;
} else {
log.info("\n >>>>>>>接口调用失败<<<<<<<");
}
return "";
}
/**
* 解析结果参数
* @param jsonResponse
* @return
*/
private static String parseResponse(String jsonResponse) {
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonResponse);
int code = jsonNode.get("code").asInt();
if (code == 200) {
return jsonNode.get("data").asText();
} else {
return "";
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。