Java Http文件上传/下载

1、Http文件上传、下载

1.1文件上传(有HTTP、HTTPS两种)

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author: zhangwch
 * @create: 2020-10-17 00:31
 **/
public class UploadTest {
    
    
    // 可以设置为Https,如:private static HttpsURLConnection conn = null;
    private static HttpURLConnection conn = null;
    private static InputStream in = null;
    private static final String DEFAULT_CHARSET = "utf-8";

    // HTTP
    public static void main(String[] args) throws Exception {
    
    
        String url = "http://127.0.0.1:8080/upload";
        String body = "{\n" +
            "    \"AA\": {\n" +
            "        \"BB\": \"123123123123\",\n" +
            "        \"CC\":\"1\"\n" +
            "    }\n" +
            "}";
        List<String> fileList = new ArrayList<>();
        fileList.add("155.pdf");
        fileList.add("116.pdf");
        fileList.add("b21f95a9eeecbba7a6693e83caed31c.jpg");
        fileList.add("001.txt");
        sends(body, fileList, url, null);
        receives();
    }

    // HTTPS
    public static void main(String[] args) throws Exception {
    
    
        String url = "https://127.0.0.1:8080/upload";

        String body = "{\n" +
            "    \"AA\": {\n" +
            "        \"BB\": \"123123123123\",\n" +
            "        \"CC\":\"1\"\n" +
            "    }\n" +
            "}";

        List<String> fileList = new ArrayList<>();
        fileList.add("155.pdf");
        fileList.add("116.pdf");
        fileList.add("b21f95a9eeecbba7a6693e83caed31c.jpg");
        fileList.add("001.txt");
        // 需开启代理(需开启代理工具,如:Fiddler)
        sends(body, fileMap, url, new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)));
        receives();
    }

    public static void sends(String body,List<String> fileList, String urlString, Proxy proxy) throws Exception {
    
    
        OutputStream out = null;
        try {
    
    
            // 构造URL
            URL url = new URL(urlString);
            if (null != proxy) {
    
    
                System.out.println("===================代理================");
                // 忽略ssl证书不信任
                SslUtil.ignoreSsl();
                // 打开连接
                conn = (HttpURLConnection) url.openConnection(proxy);
            } else {
    
    
                conn = (HttpURLConnection) url.openConnection();
            }
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //设置请求超时为15s
            conn.setConnectTimeout(15 * 1000);
            conn.setRequestMethod("POST");

            String end = "\r\n";
            String twoHyphens = "--";
            String boundary = "--------------------------" + System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            out = new DataOutputStream(conn.getOutputStream());

            if (null != body && !"".equals(body)) {
    
    
                StringBuilder sd = new StringBuilder();
                sd.append(twoHyphens + boundary + end);
                /**
                 * name = "params" : params需与服务端接收参数对应,否则会报错
                 */
                sd.append("Content-Disposition: form-data; name=\"params\"" + end + end);
                sd.append(body);
                sd.append(end);
                out.write(sd.toString().getBytes());
            }

            for (int i = 0; i < fileList.size(); i++) {
    
    
                StringBuilder fileSd = new StringBuilder();
                String fileName = fileList.get(i);
                fileSd.append(twoHyphens + boundary + end);
                /**
                 * name = "file" : file需与服务端接收参数对应,否则会报错
                 */
                fileSd.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"",
                        fileName) + end + end);
                out.write(fileSd.toString().getBytes());
                // HttpDownloadUtil.download():返回落盘到本地的文件的全路径
                write(out, "C:\\Users\\Administrator\\Desktop\\" + fileName);
                out.write(end.getBytes());
            }
            out.write((twoHyphens + boundary + twoHyphens + end).getBytes());
            out.flush();
        } catch (IOException e) {
    
    
            throw e;
        } finally {
    
    
            if (null != out) {
    
    
                try {
    
    
                    out.close();
                } catch (IOException e) {
    
    
                    throw e;
                }
            }

        }
    }

    public static void write(OutputStream out, String filePath) throws IOException {
    
    
        File file = new File(filePath);
        DataInputStream in = null;
        try {
    
    
            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);
            }
        } catch (Exception e) {
    
    
            throw e;
        } finally {
    
    
            in.close();
        }
    }

    public static void receives() throws IOException {
    
    
        // TODO Auto-generated method stub
        String charset = getResponseCharset(conn.getContentType());
        byte[] rbuf = null;
        InputStream es = conn.getErrorStream();
        try {
    
    
            in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "ISO8859-1"));
            String line;
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
    
    
                buffer.append(line);
            }
            rbuf = buffer.toString().getBytes("ISO8859-1");
        } catch (UnsupportedEncodingException e) {
    
    
            // TODO Auto-generated catch block
            throw e;
        } catch (IOException e) {
    
    
            // TODO Auto-generated catch block
            throw e;

        } finally {
    
    
            if (es != null) {
    
    
                try {
    
    
                    es.close();
                } catch (IOException e) {
    
    
                    throw e;
                }
            }
            if (in != null) {
    
    
                try {
    
    
                    in.close();
                } catch (IOException e) {
    
    
                    throw e;
                }
            }
            if (conn != null) {
    
    
                conn.disconnect();
            }
        }
        String res = new String(rbuf);
        System.out.println("receive:\n" + res);
    }

    private static String getResponseCharset(String ctype) {
    
    
        String charset = DEFAULT_CHARSET;

        if (null != ctype && !"".equals(ctype)) {
    
    
            String[] params = ctype.split(";");
            for (String param : params) {
    
    
                param = param.trim();
                if (param.startsWith("charset")) {
    
    
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
    
    
                        if (null != pair[1] && !"".equals(pair[1])) {
    
    
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }
        return charset;
    }
}

  • HTTPS-SSL处理:
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SslUtil {
    
    
    private static void trustAllHttpsCertificates() {
    
    
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new miTM();
        trustAllCerts[0] = tm;

        SSLContext sc = null;
        try {
    
    
            //TLS
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, null);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    static class miTM implements TrustManager,X509TrustManager {
    
    
        public X509Certificate[] getAcceptedIssuers() {
    
    
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
    
    
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
    
    
            return true;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
            throws CertificateException {
    
    
            return;
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType)
            throws CertificateException {
    
    
            return;
        }
    }

    public static CloseableHttpClient createSSLClientDefault(){
    
    
        try {
    
    
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy(){
    
    
                //信任所有
                public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException{
    
    
                    return true; }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
    
    
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
    
    
            e.printStackTrace();
        } catch (KeyStoreException e) {
    
    
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    /**
     * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
     * @throws Exception
     */
    public static void ignoreSsl() throws Exception{
    
    
        HostnameVerifier hv = new HostnameVerifier() {
    
    
            public boolean verify(String urlHostName, SSLSession session) {
    
    
                System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                return true;
            }
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

}

1.2 Http文件下载

/**
 * 下载文件
 *
 * @param fileName 文件名
 * @param uploadUrl 上传url
 * @param savePath 文件保存路径
 * @return
 * @throws Exception
 */
public static String download(String fileName, String downloadUrl, String savePath) throws Exception {
    
    
    //计时开始
    long begin = System.currentTimeMillis();
    //判断目录是否存在
    File file = new File(savePath);
    File path = file.getParentFile();
    if (!path.exists()) {
    
    
        path.mkdirs();
    }
    // 构造URL
    URL url = new URL(downloadUrl);
    // 打开连接
    URLConnection con = null;
    // 输入流
    InputStream is = null;
    FileOutputStream os = null;
    File sf = null;
    try {
    
    
        //打印信息
        System.out.println("文件下载请求URL[%s],文件存放路径[%s]", url, localFilePath);
        con = url.openConnection();
        con.setRequestProperty("Accept", "*/*");
        con.setRequestProperty("Connection", "keep-alive");
        // 请求头赋值文件信息
        HttpUtil.setReqHeader(con, fileName);
        //设置请求超时为15s
        con.setConnectTimeout(15 * 1000);
        is = con.getInputStream();
        byte[] getData = HttpUtil.readInputStream(is);
        os = new FileOutputStream(path);
        // 开始读取
        os.write(getData);
    } catch (IOException ie) {
    
    
        System.out.println("io异常:%s", ie.getMessage());
        throw ie;
    } catch (Exception e) {
    
    
        System.out.println("文件下载异常:%s", e.getMessage());
        throw e;
    } finally {
    
    
        if (null != os) {
    
    
            os.close();
        }
        if (null != is) {
    
    
            is.close();
        }
    }
    long end = System.currentTimeMillis();
    System.out.println("文件下载耗时:" + (end - begin) / 1000 + "s");
    return localFilePath;
}

/**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
public static byte[] readInputStream(InputStream inputStream) throws IOException {
    
    
    String logFile = PubUtil.getLogFile();
    byte[] buffer = new byte[1024];
    int len = 0;
    ByteArrayOutputStream bos = null;
    try {
    
    
        bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
    
    
            bos.write(buffer, 0, len);
        }
    } catch (IOException e) {
    
    
        TrcLog.info(logFile, "IO异常:%s", e.getMessage());
        throw e;
    } finally {
    
    
        if (null != bos) {
    
    
            bos.close();
        }
    }
    return bos.toByteArray();
}

猜你喜欢

转载自blog.csdn.net/zhangwenchao0814/article/details/109147886