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的形式拼接到地址后面

你可能感兴趣的:(网络通信,java)