当前位置: 首页 > article >正文

java发送媒体类型为multipart/form-data的请求

文章目录

public static String sendMultipartFormDataPostRequest(String urlString, String data) throws IOException {
        String fullUrl = urlString + "?" + data;
        log.info("完整请求路径为{}", fullUrl);
        URL url = new URL(fullUrl);
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 允许输入输出流
            connection.setDoInput(true);
            connection.setDoOutput(true);

            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");

            // 创建请求体输出流
//            OutputStream outputStream = connection.getOutputStream();
//            PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);

            // 添加请求体结束边界
//            writer.flush();

            // 关闭流
//            writer.close();
//            outputStream.close();

            // 发送请求并获取响应
            int responseCode = connection.getResponseCode();
            String responseMessage = connection.getResponseMessage();
            // 输出响应结果
            log.info("Response Code: {} Response Message: {}" , responseCode, responseMessage);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            return response.toString();
        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭连接
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

数据可以和get请求一样用&分隔key=value的形式拼接到地址后面


http://www.kler.cn/news/137136.html

相关文章:

  • Ubuntu22.04 制作系统ISO镜像
  • PRCV2024:可信AI向善发展与智能文档加速构建
  • 从零学习大模型(一)-----GPT3(上)
  • SVN 小乌龟 下载地址
  • 十四、MySQL事务日志
  • vue3纯前端验证码示例
  • 2022最新版-李宏毅机器学习深度学习课程-P51 BERT的各种变体
  • 基于Cortex®-M4F的TM4C123GH6NMRT7R 32位MCU,LM74900QRGERQ1、LM74930QRGERQ1汽车类理想二极管
  • 计算机网络的发展
  • 获取所有非manager的员工emp_no
  • mac添加Chrome插件的方法
  • 【华为OD题库-026】通过软盘拷贝文件-java
  • DITTEL控制器维修SENSITRON6-2AE
  • chrome 插件 Mobile simulator
  • 没收到Win11 23H2正式版的推送怎么升级到23H2
  • 第1关:图的邻接表存储及求邻接点操作
  • 让别人访问电脑本地
  • java算法学习索引之数组矩阵问题
  • 第2关:图的深度优先遍历
  • 重装系统后如何恢复以前的文件?详细教程大揭秘!
  • 进程和线程( Process and Thread)
  • python -opencv形态学操作
  • Codeforces Round 910 (Div. 2) --- B-E 补题记录
  • 1.0 Zookeeper 教程
  • 用二维码进行人员管理,人员信息一目了然
  • 深度剖析倍增算法求解最近公共祖先(LCA)的细枝末节