import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestClient {
@Autowired
LoadBalancerClient loadBalancerClient;
@Autowired
RestTemplate restTemplate;
//远程请求spring security获取令牌
@Test
public void testClient(){
//从eureka中获取认证服务的一个实例的地址
ServiceInstance serviceInstance = loadBalancerClient.choose("");
//此地址就是http://ip:port
URI uri = serviceInstance.getUri();
//令牌申请的地址 http://localhost:40400/auth/oauth/token
String authUrl = uri+ "/auth/oauth/token";
//定义header
LinkedMultiValueMap<String, String> header = new LinkedMultiValueMap<>();
//outh_client_detail 数据库表中的client_id 和 密码
String httpBasic = getHttpBasic("", "");
//固定写法
header.add("Authorization",httpBasic);
//定义body
LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<>();
//固定写法
body.add("grant_type","password");
//账户名密码
body.add("username","");
body.add("password","");
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, header);
//设置restTemplate远程调用时候,对400和401不让报错,正确返回数据
restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
@Override
public void handleError(ClientHttpResponse response) throws IOException {
if(response.getRawStatusCode()!=400 && response.getRawStatusCode()!=401){
super.handleError(response);
}
}
});
ResponseEntity<Map> exchange = restTemplate.exchange(authUrl, HttpMethod.POST, httpEntity, Map.class);
//申请令牌信息
Map bodyMap = exchange.getBody();
System.out.println(bodyMap);
}
//获取httpbasic的串
private String getHttpBasic(String clientId,String clientSecret){
String string = clientId+":"+clientSecret;
//将串进行base64编码
byte[] encode = Base64Utils.encode(string.getBytes());
//固定写法 Basic+空格+Base64加密以后的clientId+":"+clientSecret
return "Basic "+new String(encode);
}
}
远程调用单元测试+远程请求spring security获取令牌
最新推荐文章于 2025-01-24 16:00:24 发布