All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.net.wanmo.common.http.HttpUtil Maven / Gradle / Ivy

There is a newer version: 1.3.9
Show newest version
package cn.net.wanmo.common.http;

import cn.net.wanmo.common.charset.CharsetUtil;
import cn.net.wanmo.common.http.enums.Method;
import cn.net.wanmo.common.http.pojo.ResData;
import cn.net.wanmo.common.http.pojo.ResType;
import cn.net.wanmo.common.http.pojo.UploadFile;
import cn.net.wanmo.common.http.pojo.Uploader;
import cn.net.wanmo.common.http.ssl.NullHostNameVerifier;
import cn.net.wanmo.common.http.ssl.SSLContextFactory;
import cn.net.wanmo.common.http.util.ResUtil;
//import cn.net.wanmo.common.pojo.HttpResult;
import cn.net.wanmo.common.result.HttpResult;
import cn.net.wanmo.common.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.*;

public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 设置连接主机超时
     */
    public static Integer connectTimeout = 3000;
    /**
     * 设置从主机读取数据超时
     */
    public static Integer readTimeout = 10000;
    /**
     * 服务器证书文件
     */
    public static String certFilePath = "";
    /**
     * 服务器证书密码
     */
    public static String certFilePassword = "";
    /**
     * 响应解析,默认编码
     */
    public static Charset postReqBodyCharset = CharsetUtil.UTF8;

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url 发送请求的URL
     * @return 远程资源的响应结果
     */
    public static HttpResult get(String url) {
        return get(url, null, null);
    }


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url    发送请求的URL
     * @param params 请求参数,请求参数应该是 name1=value1&name2=value2 的形式
     * @return 远程资源的响应结果
     */
    public static HttpResult get(String url, String params) {
        return get(url, null, params);
    }


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url    发送请求的URL
     * @param header 通用的请求属性
     * @return 远程资源的响应结果
     */
    public static HttpResult get(String url, Map header) {
        return get(url, header, null);
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url    发送请求的URL
     * @param header 通用的请求属性
     * @param params 请求参数,请求参数应该是 name1=value1&name2=value2 的形式
     * @return 远程资源的响应结果
     */
    public static HttpResult get(String url, Map header, String params) {
        if (StringUtil.isNotBlank(params)) {
            url = url + "?" + params;
        }
        return sendResAsString(url, Method.get, header, null, null, null);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url     发送请求的 URL
     * @param reqBody 请求体
     * @return 远程资源的响应结果
     */
    public static HttpResult post(String url, String reqBody) {
        return post(url, null, reqBody, null, ResType.string);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult post(String url, Map params) {
        return post(url, null, null, params, ResType.string);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url     发送请求的 URL
     * @param reqBody 请求体
     * @return 远程资源的响应结果
     */
    public static HttpResult post(String url, Map header, String reqBody) {
        return post(url, header, reqBody, null, ResType.string);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult post(String url, Map header, Map params) {
        return post(url, header, null, params, ResType.string);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url     发送请求的 URL
     * @param header  通用的请求属性
     * @param reqBody 请求体
     * @return 远程资源的响应结果
     */
    public static HttpResult post(String url, Map header, String reqBody, Map params, ResType resType) {
        HttpResult result;
        switch (resType) {
            case file:
                result = sendResAsFile(url, Method.post, header, reqBody, params, null);
                break;
            default:
                result = sendResAsString(url, Method.post, header, reqBody, params, null);
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url     发送请求的 URL
     * @param reqBody 请求体
     * @return 远程资源的响应结果
     */
    public static HttpResult postJson(String url, String reqBody) {
        return postJson(url, null, reqBody, ResType.string);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url     发送请求的 URL
     * @param header  通用的请求属性
     * @param reqBody 请求体
     * @return 远程资源的响应结果
     */
    public static HttpResult postJson(String url, Map header, String reqBody) {
        return postJson(url, header, reqBody, ResType.string);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url     发送请求的 URL
     * @param header  通用的请求属性
     * @param reqBody 请求体
     * @return 远程资源的响应结果
     */
    public static HttpResult postJson(String url, Map header, String reqBody, ResType resType) {
        Map headerInner = getHeaderJson();
        if (MapUtil.isNotEmpty(header)) {
            headerInner.putAll(header);
        }

        return post(url, headerInner, reqBody, null, resType);
    }

    public static Map getHeaderJson() {
        Map header = new HashMap<>();
        // 代表发送端(客户端|服务器)发送的实体数据的数据类型
        header.put("Content-Type", "application/json; charset=UTF-8");
        // 代表发送端(客户端)希望接受的数据类型
        header.put("accept", "application/json");
        return header;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult upload(String url, Uploader uploader) {
        return upload(url, null, uploader, null);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult upload(String url, Uploader uploader, Map params) {
        return upload(url, null, uploader, params);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult upload(String url, Map header, Uploader uploader) {
        return upload(url, header, uploader, null);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult upload(String url, Map header, Uploader uploader, Map params) {
        List uploaderList = new ArrayList<>();
        uploaderList.add(uploader);

        return upload(url, header, uploaderList, params);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult upload(String url, List uploaderList) {
        return upload(url, null, uploaderList, null);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult upload(String url, List uploaderList, Map params) {
        return upload(url, null, uploaderList, params);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult upload(String url, Map header, List uploaderList) {
        return upload(url, header, uploaderList, null);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 远程资源的响应结果
     */
    public static HttpResult upload(String url, Map header, List uploaderList, Map params) {
        logger.debug("文件上传请求:{}", url);
        return sendResAsString(url, Method.upload, header, null, params, uploaderList);
    }


    /**
     * 发起 HTTP 请求并获取结果
     *
     * @param url          请求地址
     * @param method       请求方式(GET、POST)
     * @param header       通用的请求属性
     * @param reqBody      请求体
     * @param uploaderList 上传文件
     * @return 响应的字符串
     */
    public static HttpResult sendResAsString(String url, Method method, Map header, String reqBody, Map params, List uploaderList) {
        HttpResult result = new HttpResult();

        HttpURLConnection conn = null;
        try {
            conn = getConnection(url, method, header, reqBody, params, uploaderList);
            result.setCode(conn.getResponseCode());
            result.setMsg("Http请求完成");

            String charset = ResUtil.getResponseCharset(conn.getContentType());
            String resBody = ResUtil.getResAsString(conn.getInputStream(), charset);
            Map> headerFields = conn.getHeaderFields();

            result.setData(ResData.build(resBody, headerFields));
            logger.debug("响应数据: {}", result.getData());
        } catch (Exception e) {
            result.error("Http请求发生异常: " + e.getMessage());
            logger.error("Http请求发生异常: " + url, e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        logger.debug("响应结果:代码 {} , 消息 {}", result.getCode(), result.getMsg());
        return result;
    }

    /**
     * 发起 HTTP 请求并获取结果
     *
     * @param url          请求地址
     * @param method       请求方式(GET、POST)
     * @param header       通用的请求属性
     * @param reqBody      请求体
     * @param uploaderList 上传文件
     * @return 响应的文件
     */
    public static HttpResult sendResAsFile(String url, Method method, Map header, String reqBody, Map params, List uploaderList) {
        HttpResult result = new HttpResult();
        HttpURLConnection conn = null;
        long startTime = DateUtil.nowLong();

        try {
            conn = getConnection(url, method, header, reqBody, params, uploaderList);
            result.setCode(conn.getResponseCode());
            result.setMsg("Http请求完成");

            InputStream is = conn.getInputStream(); // 请求后远程返回的数据
            File file = ResUtil.getResAsFile(is);
            Map> headerFields = conn.getHeaderFields();

            result.setData(ResData.build(file.getAbsolutePath(), headerFields));
            logger.debug("响应数据: {}", result.getData());
        } catch (Exception e) {
            result.error("Http请求发生异常: " + e.getMessage());
            logger.error("Http请求发生异常: " + url, e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        result.setConsumeTime(DateUtil.nowLong() - startTime);
        logger.debug("响应结果:代码 {} , 消息 {}", result.getCode(), result.getMsg());
        return result;
    }

    public static HttpURLConnection getConnection(String httpUrl, Method method, Map header, String reqBody, Map params, List uploaderList) throws Exception {
        logger.debug("请求URL: {}", httpUrl);
        logger.debug("请求方式: {}", method);
        logger.debug("请求头: {}", JSON.toJSONString(header, true));
        logger.debug("请求数据: {}", reqBody);
        logger.debug("请求文件: {}", JSON.toJSONString(uploaderList, true));

        URL url = new URL(httpUrl);

        HttpURLConnection conn = null;
        if ("HTTPS".equals(url.getProtocol().toUpperCase())) { // 如果是安全连接则需要
            conn = getConnectionHttps(url);
        } else {
            conn = getConnectionHttp(url);
        }

        initConnection(conn, header);

        switch (method) { // 根据请求方式,初始化 conn
            case get:
                initGet(conn);
                break;
            case post:
                initPost(conn, reqBody, params);
                break;
            case upload:
                initUpload(conn, params, uploaderList);
                break;
            default:
                throw new RuntimeException("不支持的请求方式:" + method);
        }

        conn.connect();
        return conn;
    }


    private static void initConnection(HttpURLConnection conn, Map header) {
        { // 设置超时
            conn.setConnectTimeout(connectTimeout); // 设置连接主机超时(单位:毫秒)
            conn.setReadTimeout(readTimeout); // 设置从主机读取数据超时(单位:毫秒)
        }

        { // 设置常规属性
            /*
             * 设置请求头或响应头:HTTP请求允许一个key带多个用逗号分开的values,但是HttpURLConnection只提供了单个操作的方法:
             * setRequestProperty(key,value):会覆盖已经存在的key的所有values,有清零重新赋值的作用
             * addRequestProperty(key,value):是在原来key的基础上继续添加其他value
             */
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            conn.setRequestProperty("accept", "*/*"); // 设置接受的文件类型,*表示一切可以接受的
            conn.setRequestProperty("Accept-Charset", "UTF-8"); // 新添加的请求头编码
            conn.setRequestProperty("connection", "Keep-Alive"); // 设置维持长连接
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 设定传送的内容类型是可序列化的java对象
            // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
            // conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
        }

        if (MapUtil.isNotEmpty(header)) { // 属性覆盖或新增
            for (Map.Entry entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
    }

    private static void initGet(HttpURLConnection conn) throws Exception {
        // 设置请求方式 GET
        conn.setRequestMethod(Method.get.getValue());

        // 设置是否使用缓存 默认是true
        conn.setUseCaches(true);
    }

    private static void initPost(HttpURLConnection conn, String reqBody, Map params) throws Exception {
        // 设置请求方式 POST
        conn.setRequestMethod(Method.post.getValue());
        // 设置是否从 httpUrlConnection 允许读入,默认情况下是 true;
        conn.setDoInput(true);
        // 默认情况下是 false; 设置是否向 httpUrlConnection 允许输出,因为这个是 post 请求,参数要放在 HTTP 正文内,因此需要设为t rue,
        conn.setDoOutput(true);
        // Post 请求不能使用缓存
        conn.setUseCaches(false);

        if (MapUtil.isNotEmpty(params)) { // params 优先级高
            reqBody = toParamStr(params);
        }

        byte[] paramsBytes = StringUtil.isBlank(reqBody) ? null : reqBody.getBytes(postReqBodyCharset);

        { // 当有数据需要提交时,请求参数传给服务器

            { // 方式一
                conn.getOutputStream().write(paramsBytes);
            }

            { // 方式二
//					DataOutput dataOutput = new DataOutputStream(conn.getOutputStream());
//					dataOutput.write(paramsBytes);
            }
        }
    }

    private static void initUpload(HttpURLConnection conn, Map params, List uploaderList) throws Exception {
        conn.setConnectTimeout(3 * 1000);
        conn.setReadTimeout(30 * 60 * 1000);
        conn.setRequestProperty("Connection", "Keep-Alive");
        initUpload01(conn, params, uploaderList);
    }

    private static void initUpload01(HttpURLConnection conn, Map params, List uploaderList) throws Exception {
        final String CRLF = "\r\n";
        final String TWO_HYPHEN = "--";
        final String BOUNDARY = "----WebKitFormBoundary" + IdGen.uuid();
//        final String BOUNDARY = "===" + Long.toHexString(System.currentTimeMillis()) + "===";

        // 设置请求方式
        conn.setRequestMethod(Method.upload.getValue());
        // 设置是否从httpUrlConnection允许读入,默认情况下是true;
        conn.setDoInput(true);
        // 默认情况下是false; 设置是否向httpUrlConnection允许输出,因为这个是post请求,参数要放在 HTTP 正文内,因此需要设为true
        conn.setDoOutput(true);
        // Post 请求不能使用缓存
        conn.setUseCaches(false);
        // 判断上传文件对象是否为空
        if (CollectionUtil.isEmpty(uploaderList)) {
            logger.error("待上传的文件不能为空");
            return;
        }

        conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        conn.setRequestProperty("Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + BOUNDARY); // 定义数据分隔线
        conn.setRequestProperty("Content-Length", String.valueOf(BOUNDARY.length())); // 设置 boundary 的长度

//        OutputStream out = new DataOutputStream(conn.getOutputStream());  // 获取输出流
        OutputStream out = conn.getOutputStream();  // 获取输出流

        { // 设置请求表单参数
            {
                if (MapUtil.isEmpty(params)) {
                    params = new HashMap<>();
                }
                params.putIfAbsent("description", "文件上传");
            }

            for (Map.Entry entry : params.entrySet()) {
                StringBuilder paramData = new StringBuilder();
                paramData.append(TWO_HYPHEN).append(BOUNDARY).append(CRLF);
                paramData.append("Content-Disposition: form-data; name=" + entry.getKey()).append(CRLF);
                paramData.append("Content-Type: text/plain; charset=utf-8").append(CRLF);
                paramData.append("Content-Transfer-Encoding: 8bit").append(CRLF);
                paramData.append(CRLF); // 参数头设置完以后需要两个换行,然后才是参数内容
                paramData.append(entry.getValue());
                paramData.append(CRLF);
                out.write(paramData.toString().getBytes());
                out.flush();
            }
        }

        { // 文件上传
            for (Uploader uploader : uploaderList) {
                List files = uploader.getFiles();
                if (CollectionUtil.isNotEmpty(files)) {
                    for (int i = 0; i < files.size(); i++) {
                        UploadFile uploadFile = files.get(i);

                        if (uploadFile.getFile() == null || uploadFile.getFile().exists() == false) {
                            logger.error("待上传的文件不存在:{}", uploadFile.getFile().getAbsolutePath());
                            continue;
                        }

                        { // 开始构建 multipart/form-data 格式的数据包
                            StringBuilder mediaData = new StringBuilder();
                            mediaData.append(TWO_HYPHEN).append(BOUNDARY).append(CRLF);
                            mediaData.append("Content-Disposition: form-data; name=" + uploader.getName() + "; filename=" + uploadFile.getFilename() + "; digest=" + uploadFile.getDigest() + CRLF);
//                            mediaData.append("Content-Type:application/octet-stream" + CRLF);
                            mediaData.append("Content-Type:" + URLConnection.guessContentTypeFromName(uploadFile.getFile().getName()) + "; charset=UTF-8" + CRLF);
                            mediaData.append("Content-Transfer-Encoding: binary" + CRLF);
                            mediaData.append(CRLF); // 参数头设置完以后需要两个换行,然后才是参数内容
                            out.write(mediaData.toString().getBytes());
                            out.flush();
                        }
                        { // 文件上传
                            DataInputStream fs = new DataInputStream(new FileInputStream(uploadFile.getFile()));
                            int bytes = 0;
                            byte[] bufferOut = new byte[1024];
                            while ((bytes = fs.read(bufferOut)) != -1) {
                                out.write(bufferOut, 0, bytes);
                            }
                            out.flush();
                            IOUtils.closeQuietly(fs);
                        }

                        { // 多个文件时,二个文件之间加入这个
                            if ((i + 1) < files.size()) { // 说明还有下一个
                                out.write(CRLF.getBytes());
                                out.flush();
                            }
                        }
                    }

                }
            }
            out.flush();
        }

        { // 请求截止
            byte[] end_data = (CRLF + TWO_HYPHEN + BOUNDARY + TWO_HYPHEN + CRLF).getBytes();
            out.write(end_data);
            out.flush();
        }

        {
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 该方法是用来参考,不实际使用
     *
     * @param conn
     * @param params
     * @param uploaderList
     * @throws Exception
     */
    private static void initUpload02(HttpURLConnection conn, Map params, List uploaderList) throws Exception {
        final String CRLF = "\r\n", TWO_HYPHEN = "--", BOUNDARY = "----WebKitFormBoundary" + IdGen.uuid();

        // 设置请求方式
        conn.setRequestMethod(Method.upload.getValue());
        // 设置是否从httpUrlConnection允许读入,默认情况下是true;
        conn.setDoInput(true);
        // 默认情况下是false; 设置是否向httpUrlConnection允许输出,因为这个是post请求,参数要放在 HTTP 正文内,因此需要设为true
        conn.setDoOutput(true);
        // Post 请求不能使用缓存
        conn.setUseCaches(false);
        // 判断上传文件对象是否为空
        if (CollectionUtil.isEmpty(uploaderList)) {
            logger.error("待上传的文件不能为空");
            return;
        }

//        conn.setRequestProperty("Connection", "Keep-Alive"); // 设置为长连接
//        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        conn.setRequestProperty("Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + BOUNDARY); // 定义数据分隔线
        conn.setRequestProperty("Content-Length", String.valueOf(BOUNDARY.length())); // 设置 boundary 的长度

//        OutputStream out = new DataOutputStream(conn.getOutputStream());  // 获取输出流
        OutputStream output = conn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);

        { // 设置请求表单参数
            {
                if (MapUtil.isEmpty(params)) {
                    params = new HashMap<>();
                }
                params.putIfAbsent("description", "文件上传");
            }

            for (Map.Entry entry : params.entrySet()) {
                /*StringBuilder paramData = new StringBuilder();
                paramData.append(TWO_HYPHEN).append(BOUNDARY).append(CRLF);
                paramData.append("Content-Disposition: form-data; name=" + entry.getKey() + "").append(CRLF);
                paramData.append("Content-Type: text/plain; charset=utf-8").append(CRLF);
//                paramData.append("Content-Transfer-Encoding: 8bit").append(CRLF);
                paramData.append(CRLF); // 参数头设置完以后需要两个换行,然后才是参数内容
                paramData.append(entry.getValue());
                paramData.append(CRLF);
                out.write(paramData.toString().getBytes(postReqBodyCharset));
                out.flush();*/

                writer.append(TWO_HYPHEN).append(BOUNDARY).append(CRLF)
                        .append("Content-Disposition: form-data; name=" + entry.getKey() + "").append(CRLF)
                        .append("Content-Type: text/plain; charset=utf-8").append(CRLF)
                        .append(CRLF)
                        .append(entry.getValue().toString())
                        .append(CRLF)
                        .flush();
            }
        }

        { // 文件上传
            for (Uploader uploader : uploaderList) {
                List files = uploader.getFiles();
                if (CollectionUtil.isNotEmpty(files)) {
                    for (UploadFile uploadFile : files) {
                        if (uploadFile.getFile() == null || uploadFile.getFile().exists() == false) {
                            logger.error("待上传的文件不存在:{}", uploadFile.getFile().getAbsolutePath());
                            continue;
                        }

                        { // 开始构建 multipart/form-data 格式的数据包
                            /*StringBuilder mediaData = new StringBuilder();
                            mediaData.append(TWO_HYPHEN).append(BOUNDARY).append(CRLF);
                            mediaData.append("Content-Disposition: form-data; name=" + uploader.getName() + "; filename=" + uploadFile.getFilename() + CRLF);
//                            mediaData.append("Content-Disposition: form-data; name=" + uploader.getName() + "; filename=" + uploadFile.getFilename() + "; digest=\"" + uploadFile.getDigest() + "\"" + CRLF);
//                            mediaData.append("Content-Type:application/octet-stream" + CRLF);
                            mediaData.append("Content-Type:" + URLConnection.guessContentTypeFromName(uploadFile.getFile().getName()) + "; charset=UTF-8" + CRLF);

                            mediaData.append("Content-Transfer-Encoding: binary" + CRLF);
//                            mediaData.append("Content-Transfer-Encoding: 8bit" + CRLF);
                            mediaData.append(CRLF); // 参数头设置完以后需要两个换行,然后才是参数内容
                            out.write(mediaData.toString().getBytes(postReqBodyCharset));
                            out.flush();*/

                            writer.append(TWO_HYPHEN).append(BOUNDARY).append(CRLF)
                                    .append(
                                            new StringBuilder("Content-Type:")
                                                    .append(URLConnection.guessContentTypeFromName(uploadFile.getFile().getName()))
                                                    .append("; charset=UTF-8")
                                    )
                                    .append(CRLF)
                                    .append("Content-Transfer-Encoding: binary")
                                    .append(CRLF)
                                    .append(CRLF)
                                    .flush();
                        }
                        { // 文件上传
                            /*DataInputStream fs = new DataInputStream(new FileInputStream(uploadFile.getFile()));
                            int bytes = 0;
                            byte[] bufferOut = new byte[1024];
                            while ((bytes = fs.read(bufferOut)) != -1) {
                                out.write(bufferOut, 0, bytes);
                            }
                            out.flush();*/
//                            IOUtils.closeQuietly(fs);

                            FileInputStream fileInputStream = new FileInputStream(uploadFile.getFile());
                            int bytes = 0;
                            byte[] buffer = new byte[1024];
                            while ((bytes = fileInputStream.read(buffer)) != -1) {
                                output.write(buffer, 0, bytes);
                            }
                            output.flush();
//                            fileInputStream.close();
                        }
                        { // 多个文件时,二个文件之间加入这个
//                            out.write(CRLF.getBytes());
//                            out.flush();
//                            writer.append(CRLF).flush();
                        }
                    }
                }
            }
//            out.flush();
        }

        { // 请求截止
//            byte[] end_data = (CRLF + TWO_HYPHEN + BOUNDARY + TWO_HYPHEN + CRLF).getBytes();
//            out.write(end_data);
            writer.append(CRLF).append(TWO_HYPHEN).append(BOUNDARY).append(TWO_HYPHEN).append(CRLF).flush();
        }

        {
//            out.flush();
//            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(writer);

        }
    }


    private static HttpURLConnection getConnectionHttp(URL url) throws Exception {
        return (HttpURLConnection) url.openConnection();
    }

    private static HttpsURLConnection getConnectionHttps(URL url) throws Exception {
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new NullHostNameVerifier());
//			connectionHttps.setSSLSocketFactory(getSSLSocket());
        conn.setSSLSocketFactory(SSLContextFactory.createSSLContext(certFilePath, certFilePassword).getSocketFactory());
        return conn;
    }


    /**
     * 将map转为 参数字符串:name1=value1&name2=value2 的形式
     *
     * @param param
     * @return 字符串
     * @throws UnsupportedEncodingException
     */
    public static String toParamStr(Map param) throws UnsupportedEncodingException {
        String reStr = "";

        if (MapUtil.isEmpty(param)) {
            return reStr;
        }

        Set> entrySet = param.entrySet();
        for (Map.Entry o : entrySet) {
            if (o.getValue() == null || "null".equals(o.getValue()) || "class".equals(o.getKey())) {
                continue;
            }
            String s = o.getKey() + "=" + o.getValue();
            reStr += (s + "&");
        }

        return StringUtil.isBlank(reStr) ? "" : reStr.substring(0, reStr.length() - 1);
    }

    /**
     * 将字符串 (name1=value1&name2=value2)的形式,转为 Map 形式
     *
     * @param param
     * @return Map
     * @throws UnsupportedEncodingException
     */
    public static Map toParamMap(String param) throws UnsupportedEncodingException {
        Map paramMap = new HashMap<>();
        if (StringUtil.isBlank(param)) {
            return paramMap;
        }

        String[] paramPairsArr = param.split("&");
        for (String paramPair : paramPairsArr) {
            String[] paramPairArr = paramPair.split("=");
            if (paramPairArr.length == 2) {
                paramMap.put(paramPairArr[0].trim(), paramPairArr[1].trim());
            } else {
                paramMap.put(paramPairArr[0].trim(), "");
            }

        }

        return paramMap;
    }

    /**
     * 判断是否是 HTTP URL
     *
     * @param url 请求 url
     * @return 布尔值
     */
    public static Boolean isHttpUrl(String url) {
        boolean flag = false;

        try {
            flag = url.indexOf("://") != -1;
        } catch (Exception e) {
        }

        return flag;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy