JAVA模拟发送form-data的请求,支持大字符串

参数:
在这里插入图片描述

/**
     * 模拟发送form-data的请求
     *
     * @param params 请求参数
     * @return 返回结果
     */
    public static String formDataRequestExample(Map<String, Object> params) throws IOException {
        // 请求URL
        String requestUrl = String.valueOf(params.get("url"));
        // 构建请求参数
        String boundary = "---------------------------" + System.currentTimeMillis();
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String formDataTemplate = twoHyphens + boundary + lineEnd +
                "Content-Disposition: form-data; name=\"%s\"" + lineEnd +
                lineEnd +
                "%s" + lineEnd;
        // 构建请求体
        String requestBody = "";
        //表单中参数
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (!entry.getKey().equals("url")) {
                requestBody = requestBody + String.format(formDataTemplate, entry.getKey(), new Gson().toJson(entry.getValue()));
            }
        }
        String formData5 = String.format(formDataTemplate, "url", params.get("url"));
        // 构建请求体
        requestBody = requestBody + formData5;
        // 创建连接
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求方法为POST
        connection.setRequestMethod("POST");
        // 设置请求头
        connection.setRequestProperty("Content-Type", "multipart/form-data;  boundary=" + boundary);
        // 允许输入输出流
        connection.setDoInput(true);
        connection.setDoOutput(true);
        // 获取输出流
        OutputStream outputStream = connection.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
        // 发送请求体
        writer.append(requestBody);
        writer.flush();
        writer.close();
        // 获取响应
        int responseCode = connection.getResponseCode();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        // 断开连接
        connection.disconnect();
        return response.toString();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是一个使用Java发送form-data请求的代码示例: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; public class FormDataRequestExample { public static void main(String[] args) throws Exception { String url = "http://example.com/submitform"; Map<String, String> formData = new LinkedHashMap<>(); formData.put("firstname", "John"); formData.put("lastname", "Doe"); formData.put("email", "johndoe@example.com"); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // Set content-type header for form data con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Build form data string StringBuilder postData = new StringBuilder(); for (Map.Entry<String, String> param : formData.entrySet()) { if (postData.length() != 0) { postData.append('&'); } postData.append(param.getKey()); postData.append('='); postData.append(param.getValue()); } // Send form data con.setDoOutput(true); con.getOutputStream().write(postData.toString().getBytes("UTF-8")); // Read response BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Print response System.out.println(response.toString()); } } ``` 该代码创建了一个 `Map<String, String>` 对象,里面存储了表单数据。然后使用 `HttpURLConnection` 将请求发送到指定的 URL。在请求头中使用 `Content-Type` 指定请求体类型为 `application/x-www-form-urlencoded`。同时,使用 StringBuilder 构建表单数据字符串,并将其作为请求发送。最后,读取响应并输出。 请注意,该代码示例适用于普通的 form-data 请求,不适用于上传文件等更复杂的场景。如果需要上传文件,请参考其他资料。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值