资讯专栏INFORMATION COLUMN

java 通过 HttpURLConnection 上传文件

Tychio / 3333人阅读

摘要:直接用的上传文件,通过模拟提交方法具体代码如下网络访问工具默认默认或执行调用地址方法地址请求的与实体对应的信息如执行调用地址方法地址秒连接分钟读数据上传文件表单参数文件参数上传文件允许同一个属性上传多个文件表单参数文件参数调

直接用jdk的HttpURLConnection上传文件,通过模拟post提交方法

具体代码如下:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * http 网络访问工具
 *
 * @author wonderful.
 * @version 3.0.0
 */
public class HttpClient {

    private final static Logger LOGGER = Logger.getLogger(HttpClient.class);
    private String method = null;
    private String CONTENT_TYPE = null; //默认
    
    /**
     * 默认POST
     *
     * @return String
     */
    public String getMethod() {
        if (method == null) {
            return "POST";
        }
        return method;
    }

    /**
     *  POST 或 GET 
     *
     * @param method .
     */
    public void setMethod(String method) {
        this.method = method;
    }
    
    /**
     * 执行调用 serviceURL地址 方法
     * @param serviceURL webService地址.
     * @param param String.
     * @param ContentType 请求的与实体对应的MIME信息   如:Content-Type: application/x-www-form-urlencoded,application/json,application/xml  
     * @return String.
     */
    public String pub(String serviceURL, String param,String contentType) {
        CONTENT_TYPE = contentType;
        return pub(serviceURL,param);
    }
    /**
     * 执行调用 serviceURL地址 方法
     * @param serviceURL webService地址.
     * @param param String.
     * @return String.
     */
    public String pub(String serviceURL, String param) {
        URL url = null;
        HttpURLConnection connection = null;
        StringBuffer buffer = new StringBuffer();
        LOGGER.info("request:" + serviceURL + "?" + param);
        try {
            url = new URL(serviceURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(getMethod());
            connection.setConnectTimeout(5000);//30秒连接
            connection.setReadTimeout(5*60*1000);//5分钟读数据
            connection.setRequestProperty("Content-Length", param.length() + "");
            if(CONTENT_TYPE != null){
                connection.setRequestProperty("Content-Type", CONTENT_TYPE);
            }           
            
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(param.getBytes("UTF-8"));

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
        } catch (IOException e) {
            LOGGER.error(e);
        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }

        LOGGER.info("response:" + buffer.toString());
        return buffer.toString();
    }

    /**
     * 上传文件
     * 
     * @param serviceURL
     * @param textMap
     *            表单参数
     * @param fileMap
     *            文件参数
     * @return
     * @throws IOException
     */
    public static String formUpload(String serviceURL, Map textMap, Map fileMap) throws IOException {
        Map> tempMap = new HashMap<>();
        if (!Objects.isNull(fileMap) && !fileMap.isEmpty()) {
            Iterator> iter = fileMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = iter.next();
                String inputName = entry.getKey();
                String inputValue = entry.getValue();
                if (StringUtils.isAnyBlank(inputName, inputValue)) {
                    continue;
                }
                LinkedHashSet values = new LinkedHashSet<>();
                values.add(inputValue);
                tempMap.put(inputName, values);
            }
        }
        return formUploadMulti(serviceURL, textMap, tempMap);
    }

    /**
     * 上传文件,允许同一个属性上传多个文件
     * 
     * @param serviceURL
     * @param textMap
     *            表单参数
     * @param fileMap
     *            文件参数
     * @return
     * @throws IOException
     */
    public static String formUploadMulti(String serviceURL, Map textMap, Map> fileMap) throws IOException {
        LOGGER.trace(String.format("调用文件上传,传入参数:serviceURL=%s,textMap=%s,fileMap=%s", serviceURL, textMap, fileMap));
        String res = "";
        HttpURLConnection conn = null;
        OutputStream out = null;
        BufferedReader reader = null;
        String BOUNDARY = "---------------------------" + System.currentTimeMillis(); // boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(serviceURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);// 30秒连接
            conn.setReadTimeout(5 * 60 * 1000);// 5分钟读数据
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            out = new DataOutputStream(conn.getOutputStream());
            // text
            if (!Objects.isNull(textMap) && !textMap.isEmpty()) {
                StringBuffer strBuf = new StringBuffer();
                Iterator> iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = iter.next();
                    String inputName = entry.getKey();
                    String inputValue = entry.getValue();
                    if (StringUtils.isAnyBlank(inputName, inputValue)) {
                        continue;
                    }
                    strBuf.append("
").append("--").append(BOUNDARY).append("
");
                    strBuf.append("Content-Disposition: form-data; name="" + inputName + ""

");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }

            // file
            if (!Objects.isNull(fileMap) && !fileMap.isEmpty()) {
                Iterator>> iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry> entry = iter.next();
                    String inputName = entry.getKey();
                    LinkedHashSet inputValue = entry.getValue();
                    if (StringUtils.isAnyBlank(inputName) || inputValue.isEmpty()) {
                        continue;
                    }
                    for (String filePath : inputValue) {
                        File file = new File(filePath);
                        String filename = file.getName();
                        Path path = Paths.get(filePath);
                        String contentType = Files.probeContentType(path);
                        StringBuffer strBuf = new StringBuffer();
                        strBuf.append("
").append("--").append(BOUNDARY).append("
");
                        strBuf.append("Content-Disposition: form-data; name="" + inputName + ""; filename="" + filename + ""
");
                        strBuf.append("Content-Type:" + contentType + "

");
                        LOGGER.trace(String.format("filename:%s,contentType:%s", filename, contentType));
                        out.write(strBuf.toString().getBytes());

                        DataInputStream in = new DataInputStream(new FileInputStream(file));
                        int bytes = 0;
                        byte[] bufferOut = new byte[1024];
                        while ((bytes = in.read(bufferOut)) != -1) {
                            out.write(bufferOut, 0, bytes);
                        }
                        in.close();
                    }
                }
            }

            byte[] endData = ("
--" + BOUNDARY + "--
").getBytes();
            out.write(endData);
            out.flush();

            // 读取返回数据
            LOGGER.trace(String.format("http 返回状态:ResponseCode=%s,ResponseMessage=%s", conn.getResponseCode(), conn.getResponseMessage()));
            StringBuffer strBuf = new StringBuffer();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("
");
            }
            res = strBuf.toString();
            LOGGER.trace(String.format("http 返回数据:%s", res));
            reader.close();
            reader = null;
        } catch (IOException e) {
            throw e;
        } finally {
            if (!Objects.isNull(out)) {
                out.close();
                out = null;
            }
            if (!Objects.isNull(reader)) {
                reader.close();
                reader = null;
            }
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
}

上面的两个方法有待优化,未处理

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/75753.html

相关文章

  • 使用java进行http通信

    摘要:请求用于注册登录等安全性较高且向数据库中写入数据的操作。该类中定义了一系列的状态码设置该连接是可以输出的设置请求方式向连接中输出数据相当于发送数据给服务器读取数据使用进行通信大大简化了中通信的实现。 Http通信概述 Http通信主要有两种方式POST方式和GET方式。前者通过Http消息实体发送数据给服务器,安全性高,数据传输大小没有限制,后者通过URL的查询字符串传递给服务器参数...

    blastz 评论0 收藏0
  • 怎么用Java从网上下载一个视频下来

    摘要:用的流从网上下载一个视频原理就是用对象与目标地址建立一个链接,用流的方式从这个链接上把视频的二进制数据读取下载然后再写入本地文件。然后循环依次写入缓存的大小,直至结束。 用Java的IO流从网上下载一个视频 原理:就是用URL对象与目标地址建立一个链接,用IO流的方式从这个链接上把视频的二进制数据读取下载然后再写入本地文件。 因为小弟比较菜的缘故,不会下载那些加了密的视频链接,这里我就...

    warmcheng 评论0 收藏0
  • 慕课网_《Java实现SSO单点登录》学习总结

    摘要:时间年月日星期三说明本文部分内容均来自慕课网。慕课网教学示例源码无个人学习源码第一章概述课程介绍及介绍课程目标认识并理解及其应用,并能根据其实现原理自行实现。 时间:2017年3月22日星期三说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学示例源码:无个人学习源码:https://github.com/zccodere/s... 第一章:概述 1-...

    flyer_dev 评论0 收藏0

发表评论

0条评论

Tychio

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<