java如何调用HTTP接口post请求

请问,java怎么调用http接口的post请求,我这边传个json过去,这代码要咋写呀

用http的工具类 直接发Post请求,封装请求体,设置请求头就行

搜一下,会有很多方法,只需要换个参数,url还有请求体的事:https://blog.csdn.net/weixin_42402326/article/details/123255517

你问题没说明白,你这边是前端还是后台接口调取另外的接口,如果是前端,jq使用ajax,vue使用axios,如果是后台接口调取另外的接口,可以使用openfeign。


/**
     * 发送POST请求
     *
     * @param url        目的地址
     * @return 远程响应结果
     */
    public static String postJSON(String url, String jsonString) throws Exception {
        String result = ""; // 返回的结果
        BufferedReader in = null; // 读取响应输入流
        PrintWriter out = null;
        try {
            // 创建URL对象
            java.net.URL connURL = new java.net.URL(url);
            // 打开URL连接
            java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
            // 设置通用属性
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            httpConn.setRequestProperty("Content-Type", "application/json");
            //httpConn.setRequestProperty("Charsert", "UTF-8"); //设置请求编码
            // 设置POST方式
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            out.write(jsonString);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应,设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                throw e;
            }
        }
        return result;
    }