• 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();
                }
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

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

  • 相关阅读:
    DockerFile微服务实战
    医会宝APP登录体验
    【物联网】NB-IoT
    所有专栏博客汇总列表
    Cn2线路异常采用Nginx反代灾备解决方案
    spring boot单元测试
    2022杭电多校第十场题解
    C语言 | Leetcode C语言题解之第129题求根节点到叶节点数字之和
    C++11 decltype 的简单使用
    NVRadar:一种实时的雷达障碍检测和占位栅格预测方法
  • 原文地址:https://blog.csdn.net/weixin_43790613/article/details/134463064