HTTP-Client

2022-10-10  本文已影响0人  0012

http传输文件

使用HttpClient实现文件传输

pom

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4.1</version>
</dependency>

核心代码

public class HttpClient {
    /**
     * 文件上传
     * @param msg         上传报文
     * @param fileName    文件名称
     * @param file        文件内容
     * @return
     */
    public String uploadFile(String msg, String fileName, byte[] file) {

        if (StringUtils.isBlank(msg) || StringUtils.isBlank(fileName)) {
            throw new NullPointerException("请求失败请检查请求报文 || 压缩包文件名");
        }
        // 创建默认的httpClient实例.
        String result = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient = null;
        try {
            httpclient = new SSLClient();
            HttpPost httpPost = new HttpPost(String.valueOf(url));
            MultipartEntityBuilder mEntityBuileder = MultipartEntityBuilder.create();
            mEntityBuileder.setCharset(Charset.forName("UTF-8"));
            mEntityBuileder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //以下两个 file msg为固定字段
            mEntityBuileder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, fileName);
            mEntityBuileder.addTextBody("msg", msg);
            httpPost.setEntity(mEntityBuileder.build());
            // 设置请求和连接超时时间
            httpPost.setConfig(RequestConfig.custom().setSocketTimeout(connectionTimeout).setConnectTimeout(connectionTimeout).setProxy(new HttpHost("localhost", 8888)).build());
            response = httpclient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity);
                    EntityUtils.consume(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            // 关闭连接,释放资源
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpclient) {
                    httpclient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读