public String uploadFile(File file, String url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
        httpPost.setConfig(requestConfig);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.setCharset(Charset.forName("UTF-8")).addBinaryBody("multipartFile", file, ContentType.MULTIPART_FORM_DATA, file.getName());
        org.apache.http.HttpEntity httpEntity = builder.build();
        httpPost.setEntity(httpEntity);
        HttpResponse httpResponse = httpclient.execute(httpPost);
        org.apache.http.HttpEntity responseEntity = httpResponse.getEntity();
        if(responseEntity!=null) {
            return EntityUtils.toString(responseEntity,Charset.forName("UTF-8"));
        }
    }catch (ClientProtocolException ex) {
        log.debug("uploadFile ClientProtocolException :", ex);
    }catch (IOException ex) {
        log.debug("uploadFile IOException :", ex);
    }
    return  null;
}

依赖

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.5</version>
            <scope>compile</scope>
        </dependency>
最后修改:2023 年 04 月 26 日
如果觉得我的文章对你有用,请随意赞赏