如何通过java代码发送文件-表单形式http请求

如何通过java代码发送文件表单http请求

1、引入包

<!-- http请求 -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>${httpcomponents.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>${httpcomponents.version}</version>
</dependency>

2、文件表单请求

//单元测试
@Test
    public void testUploadFile(){
        String url="https://xx.xxx.com/api/openapi/select";
        uploadFile(url,"C:\\Users\\xxxx\\Desktop\\test.txt","test文件.txt",null);
    }
//文件表单上传
public String uploadFile(String url, String fileUrl, String fileParamName, Map<String, String> params) {
    HttpPost httpPost = new HttpPost(url);
    CloseableHttpClient client  = HttpClientBuilder.create().build();
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout).setSocketTimeout(timeout).build();
    httpPost.setConfig(requestConfig);
    String resultString = "";
    CloseableHttpResponse response = null;
    try {
        // 把文件转换成流对象 我这里用的是文件地址,所有用ByteArrayBody,可根据实际需要使用org.apache.http.entity.mime.content包下的类型
        ByteArrayBody byteArrayBody = new ByteArrayBody(UrlUtil.bytes(fileUrl),fileParamName);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        // 相当于<input type="file" name="file"/>
        builder.addPart("file", byteArrayBody);
        // 相当于<input type="text" name="userName" value=userName>
        builder.addPart("name",
                new StringBody(fileParamName, ContentType.create("text/plain", Consts.UTF_8)));
        if (params != null) {
            for (String key : params.keySet()) {
                builder.addPart(key,
                        new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
            }
        }

        HttpEntity reqEntity = builder.build();
        httpPost.setEntity(reqEntity);
        response = client.execute(httpPost);
        // 发起请求 并返回请求的响应
        resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IoUtil.close(client);
        IoUtil.close(response);
    }
    return resultString;
}

附org.apache.http.entity.mime.content:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中使用POST请求发送form表单数据,你可以使用JavaHttpURLConnection或Apache HttpClient库来实现。这里我将提供一个使用HttpURLConnection的示例代码: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Map; public class FormPostExample { public static void main(String[] args) { String url = "http://example.com/submit-form"; // 替换为你要发送请求的URL try { // 构建请求参数 String formData = "username=johndoe&password=secretpassword"; // 创建URL对象 URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法为POST con.setRequestMethod("POST"); // 启用输入输出 con.setDoOutput(true); con.setDoInput(true); // 设置请求头信息 con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 获取DataOutputStream对象并写入请求参数 DataOutputStream out = new DataOutputStream(con.getOutputStream()); out.write(formData.getBytes(StandardCharsets.UTF_8)); out.flush(); out.close(); // 获取响应状态码 int responseCode = con.getResponseCode(); // 读取响应内容 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印响应结果 System.out.println("Response Code: " + responseCode); System.out.println("Response Content: " + response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例代码中,我们首先创建了一个URL对象来表示请求的URL。然后,我们使用HttpURLConnection来建立与该URL的连接,并设置请求方法为POST。接下来,我们启用了输入和输出流,并设置请求头信息。然后,我们将form表单数据写入DataOutputStream对象,并发送请求。最后,我们读取响应内容并打印出来。 请注意,上述示例中的URL、请求参数和请求头信息需要根据你的实际需求进行修改。此外,你还可以使用其他的HTTP客户端库来发送POST请求,例如Apache HttpClient或OkHttp等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值