SpringBoot发送带文件的Post请求

使用httpclient发送一个带文件参数的Post请求

Pom依赖

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpclient</artifactId>
		<version>4.5.3</version>
	</dependency>
	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.8</version>
    </dependency>

服务请求

@PostMapping("/upload")
public String fileForward(MultipartFile file) {

    // 这是一个开源上传图床的API
    // 参数 file : 表单文件
    // 返回值:  [{"src":"/file/5d5dd7108a93f6d1e9249.png"}]
    String url = "https://img.nickyam.com/upload";
    
	// 因为该网站不受信任,下面静态方法是信任所有网站
    // 不信任网站报 “unable to find valid certification path to requested target”
    CloseableHttpClient httpClient = getScontractHttpClient();
    String result = "";
    try {

        String fileName = file.getOriginalFilename();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        
        // 建造者模式构造参数
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // 类似浏览器表单提交,对应input的name和value
        builder.addBinaryBody("file", file.getInputStream(), 
                              ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
        HttpEntity entity = builder.build();
        
        httpPost.setEntity(entity);
		// 执行提交
        HttpResponse response = httpClient.execute(httpPost);
        // 获取响应内容
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            // 将响应内容转换为字符串
            result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return result;
}

// 信任所有的网站
public static CloseableHttpClient getScontractHttpClient() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
    //创建httpClient
    return HttpClients.custom().setSSLContext(sslContext).
        setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
}

展示

测试结果

posted @   凉冰24  阅读(615)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示