目前有一个需求是需要跨服务调用的,通过后端直接访问,直接通过url访问记录一下,后面更简单的去处理。
首先是最古老的方式HttpURLConnection
public JSONArray sendAuthorization(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("staffNo","000222");
try {
// 定义URL和凭据信息
String urlString = "http://127.0.0.1:12001/sso/sendPersonAuthorization";
// 构建URL对象
URL url = new URL(urlString);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置请求头,指定请求体格式为 JSON
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer 96228ded-0c64-4ffe-a487-c1ed0c6918bc");
// 启用输出流,并将 JSON 请求体写入连接
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(jsonObject.toString().getBytes());
os.flush();
os.close();
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONArray jsonObject1 = JSONArray.parseArray(response.toString());
return jsonObject1;
// 打印响应内容
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
处理方式相当古老了,但是别说好用还。
新的方式RestTemplate
@PostMapping("/sendPersonAuthorization")
public List<TokenVO> sendPersonAuthorization() {
// 请求URL
String url = "http://127.0.0.1:12001/login";
// 请求参数
HashMap<String, String> params = new HashMap<>();
params.put("ticket", Sm2Encryptor.encryptString("mima"));
params.put("captcha", "123");
params.put("token", "123");
// HTTP头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8); // 设置Content-Type为application/x-www-form-urlencoded
headers.set("Clientid", "bVS46ElU"); // 设置自定义HTTP头
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(null, headers);
RestTemplate restTemplate = new RestTemplate();
// 查询所有生效的用户
List<LoginUserDetailVO> voList = basePortaluserMapper.findUserInfoList();
return voList.stream().map(vo -> {
params.put("per", Sm2Encryptor.encryptString(vo.getUsername()));
// 构建带查询参数的完整URL
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
String urlWithParams = builder.toUriString();
ResponseEntity<String> response = restTemplate.exchange(urlWithParams, HttpMethod.POST, requestEntity, String.class);
String token = "Bearer " + ((JSONObject) JSON.parseObject(response.getBody()).get("data")).get("value");
TokenVO tokenVO = new TokenVO();
BeanUtils.copyProperties(vo, tokenVO);
tokenVO.setToken(token);
return tokenVO;
}).collect(Collectors.toList());
}
使用RestTemplate 方式去进行访问,使用Stream流进行返回