java远程调用post请求传JSONObject参数

时间:2025-03-18 16:14:43

java HttpClient远程调用

// 开始远程调用接口===============================================
        // 创建HttpClient对象
        CloseableHttpClient httpClient = ().setRedirectStrategy(new LaxRedirectStrategy()).build();

        // 创建http  POST请求
        HttpPost httpPost = new HttpPost("http://127.0.0.1:1234/recommender/service/");

        // 对JSONObject格式的数据进行转型
        String string = ();
        StringEntity entity = new StringEntity(string, "utf-8");
        ("UTF-8");
        ("application/json");
        (entity);
        // 设置Post参数
        ("Content-Type", "application/json;charset=UTF-8");

        CloseableHttpResponse response = null;
        String content = null;
        // 开始链接
        try {
            response = (httpPost);
            if ((response)){
                throw new ServiceException("调用接口返回数据出错");
            }
            (());

            // 判断调用状态
            if(().getStatusCode() == 200){
            // 获取返回结果
            HttpEntity httpEntity = ();
            // 结果转型为String
            content = (httpEntity, "UTF-8");
            if ((content)){
                throw new ServiceException("转型数据错误");
            }
            (content);
            }
        }catch (Exception e) {
            ();
            ("调用数据接口出错", e);
        }finally {
            if (response != null){
                ();
            }
        }
        // 链接关闭======================================================
        ();