http调用HttpURLConnection、RestTemplate

目前有一个需求是需要跨服务调用的,通过后端直接访问,直接通过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流进行返回

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又是重名了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值