java请求http服务-参数是@RequestBody String resultJson 类型

当对方的接口参数是@RequestBody类型时如何调用。

1、对方controller接口写发如下:

复制代码
 @PostMapping(value = "/test")
    @ResponseBody
    public StringresultBack(@RequestBody String  resultJson) {
        return  "helloWorld";
    }

2、Apipost的调用方式如下:

3、用java代码调用对方接口方法

(1)引入依赖

复制代码
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.10</version>
</dependency>
  
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
  
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

(2)调用方法

复制代码
 /**
     * @param httpUrl 请求的url
     * @param jsonParam 原始JSON字符串参数
     * @return 响应结果
     */
    public String doPostJson(String httpUrl, String jsonParam) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间:60000毫秒
            connection.setReadTimeout(60000);

            // 允许向服务器输出数据
            connection.setDoOutput(true);
            // 允许从服务器读取数据
            connection.setDoInput(true);

            // 设置Content-Type为application/json
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            // 如果需要设置其他请求头,如Authorization,可以在这里添加
            // connection.setRequestProperty("Authorization", "Bearer your_token_here");

            // 检查JSON参数是否为空
            if (jsonParam == null || jsonParam.trim().isEmpty()) {
                throw new IllegalArgumentException("JSON参数不能为空");
            }

            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 写入JSON参数,指定UTF-8编码
            os.write(jsonParam.getBytes("UTF-8"));
            os.flush();

            // 检查响应状态码
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                is = connection.getInputStream();
            } else {
                // 非200状态码使用错误流
                is = connection.getErrorStream();
            }

            // 处理响应流
            if (is != null) {
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                }
                result = responseCode == 200 ? sbf.toString() :
                        "Error (code: " + responseCode + "): " + sbf.toString();
            } else {
                result = "No response from server, code: " + responseCode;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            result = "URL格式错误: " + e.getMessage();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            result = "参数错误: " + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            result = "IO异常: " + e.getMessage();
        } finally {
            // 关闭资源
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开连接
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }
相关推荐
hqxstudying1 小时前
J2EE模式---前端控制器模式
java·前端·设计模式·java-ee·状态模式·代码规范·前端控制器模式
ZeroToOneDev3 小时前
Java(LinkedList和ArrayList底层分析)
java·开发语言
没有bug.的程序员5 小时前
JAVA面试宝典 -《 架构演进:从单体到 Service Mesh》
java·面试·架构
典学长编程5 小时前
Java从入门到精通!第十一天(Java常见的数据结构)
java·开发语言·数据结构
皮皮林5515 小时前
设计一个多租户 SaaS 系统,如何实现租户数据隔离与资源配额控制?
java·saas
霍格沃兹软件测试开发5 小时前
Playwright 自动化测试系列(6)| 第三阶段:测试框架集成指南:参数化测试 + 多浏览器并行执行
java·数据库·mysql·自动化
Bonnie_12156 小时前
02-netty基础-java四种IO模型
java·开发语言·nio·jetty
我不是星海6 小时前
建造者设计模式
java·开发语言
JIngJaneIL6 小时前
健身管理小程序|基于微信开发健身管理小程序的系统设计与实现(源码+数据库+文档)
java·数据库·小程序·论文·课程设计·毕设·健身管理小程序
Dcs6 小时前
Spring Framework 6.2 正式发布:开发者最值得关注的更新全览!
java