Java,Servlet实现单文件/二进制上传,Postman和HttpClient测试

单文件/二进制上传HTTP协议,请求报文包含:请求行、请求头、请求体。单文件/二进制上传协议:POST /web/upload/binary H

单文件/二进制上传

HTTP协议,请求报文包含:请求行、请求头、请求体。

单文件/二进制上传协议:

POST /web/upload/binary HTTP/1.1
header-name: header-value
Content-type: image/jpeg
User-Agent: PostmanRuntime/7.28.4
Host: 127.0.0.1:8080
Proxy-Connection: Keep-Alive
Content-Length: 1920
 
--二进制(略)

服务器端Servlet实现

Servlet实现类

package com.what21.servlet.upload;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.what21.servlet.upload.helper.HttpServletUploadHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/upload/binary")
public class BinaryUploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("code", "ok");
        // ===================================================================================//
        // ===== 解析参数&保存文件
        // ===================================================================================//
        String domain = "";  // 域
        String function = "head";  // 功能
        String storagePath = "D:/Temp/Upload/";
        try {
            HttpServletUploadHelper.Entity entity = HttpServletUploadHelper.createEntityWithHeader(request, domain, function);
            String saveFilePath = storagePath + entity.getStorageAddress();
            File file = HttpServletUploadHelper.exchangeSave(request.getInputStream(), saveFilePath);
            entity.setSize(file.length());
            dataMap.put("data", entity);
        } catch (Exception e) {
            e.printStackTrace();
            dataMap.put("code", "error");
            dataMap.put("msg", e.getMessage());
        }
        // ===================================================================================//
        // ===== 返回结果
        // ===================================================================================//
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(dataMap);
        response.setContentType("text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.flush();
    }

}

助手类

package com.what21.servlet.upload.helper;

import com.relops.snowflake.Snowflake;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

public final class HttpServletUploadHelper {

    // ===================================================================================//
    // ===== header中操作
    // ===================================================================================//

    /**
     * 从header中获取值
     *
     * @param request
     * @param name
     * @param defaultValue
     * @return
     */
    public static String getHeaderValue(HttpServletRequest request, String name, String defaultValue) {
        String value = request.getHeader(name);
        if (StringUtils.isNotEmpty(value)) {
            return value;
        }
        return defaultValue;
    }

    // ===================================================================================//
    // ===== 文件操作
    // ===================================================================================//

    /**
     * 获取文件后缀
     *
     * @param name
     * @return
     */
    public static String getFileSuffix(String name) {
        if (StringUtils.isNotEmpty(name)) {
            if (name.contains(".")) {
                return name.split("\\.")[1];
            }
        }
        return "";
    }

    /**
     * 交换保存
     *
     * @param inputStream
     * @param filename
     * @throws IOException
     */
    public static File exchangeSave(InputStream inputStream, String filename) throws IOException {
        File saveFile = new File(filename);
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdirs();
        }
        FileOutputStream output = new FileOutputStream(filename);
        int r = -1;
        byte[] bytes = new byte[512];
        while ((r = inputStream.read(bytes)) != -1) {
            output.write(bytes, 0, r);
        }
        output.flush();
        output.close();
        return saveFile;
    }

    // ===================================================================================//
    // ===== 实体操作
    // ===================================================================================//

    /**
     * 从header中取参数
     *
     * @param request
     * @param domain
     * @param function
     * @return
     * @throws IOException
     */
    public static Entity createEntityWithHeader(HttpServletRequest request, String domain, String function) throws IOException {
        Entity entity = new Entity();
        entity.setId(getSnowflakeId());
        entity.setModular(HttpServletUploadHelper.getHeaderValue(request, "modular", "communal"));
        entity.setModel(HttpServletUploadHelper.getHeaderValue(request, "model", "common"));
        entity.setName(HttpServletUploadHelper.getHeaderValue(request, "name", getRandomString(30)));
        entity.setType(HttpServletUploadHelper.getHeaderValue(request, "type", "file"));
        entity.setSuffix(HttpServletUploadHelper.getFileSuffix(entity.getName()));
        entity.setFile(entity.getId() + "." + entity.getSuffix());
        String accessAddress = "/" + entity.getModular() + "/" + entity.getModular();
        String storageAddress = "/" + entity.getModular() + "/" + entity.getModular();
        if (StringUtils.isNotEmpty(domain)) {
            accessAddress = domain + "/" + accessAddress;
            storageAddress = domain + "/" + storageAddress;
        }
        if (StringUtils.isNotEmpty(function)) {
            accessAddress = accessAddress + "/" + function;
            storageAddress = storageAddress + "/" + function;
        }
        accessAddress = accessAddress + "/" + entity.getId();
        storageAddress = storageAddress + "/" + entity.getId();
        entity.setAccessAddress(accessAddress);
        entity.setStorageAddress(storageAddress);
        entity.setStatus(0);
        return entity;
    }

    // ===================================================================================//
    // ===== 实体类
    // ===================================================================================//

    @Data
    public static class Entity {

        // 主键ID
        private Long id;

        // 系统一级模块
        private String modular;

        // 系统二级模块
        private String model;

        // 静态资源名称
        private String name;

        // 静态资源类型
        private String type;

        // 静态资源文件
        private String file;

        // 文件大小
        private Long size;

        // 静态资源后缀
        private String suffix;

        // 静态资源状态
        private Integer status;

        // 资源存储地址
        private String storageAddress;

        // 资源访问地址
        private String accessAddress;

    }

    // ===================================================================================//
    // ===== 工具操作
    // ===================================================================================//

    /**
     * @return
     */
    public static Long getSnowflakeId() {
        return getSnowflakeId(1);
    }

    /**
     * @param node
     * @return
     */
    public static Long getSnowflakeId(int node) {
        Snowflake snowflake = new Snowflake(node);
        return snowflake.next();
    }

    /**
     * 获取随机字符串
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    // ===================================================================================//
    // ===== The end
    // ===================================================================================//


}

单文件上传客户端测试

Postman测试

Java,Servlet实现单文件/二进制上传,Postman和HttpClient测试

Java,Servlet实现单文件/二进制上传,Postman和HttpClient测试

HttpClient客户端实现

HttpClient4.5相关:Java,HttpClient4.5,https连接请求调用Java,HttpClient4.5,https及使用连接池Java,Netty,HttpClient,实现代理

工具类

package com.what21.httpclient4;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

public class HttpClientHelperUtils {

    /**
     * @param url
     * @return
     */
    public static String get(String url) {
        String result = null;
        HttpEntity httpEntity = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建POST
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(getRequestConfig());
            // 设置头参数
            Header header = new BasicHeader("Accept-Encoding", null);
            httpGet.setHeader(header);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                // http请求释放资源异常
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * @param url
     * @param paramsMap
     * @return
     */
    public static String post(String url, Map<String, String> paramsMap) {
        String result = null;
        HttpEntity httpEntity = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建POST
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(getRequestConfig());
            // 设置头参数
            Header header = new BasicHeader("Accept-Encoding", null);
            httpPost.setHeader(header);
            // 添加参数
            List<NameValuePair> nameValuePairs = new ArrayList<>();
            if (paramsMap != null && paramsMap.size() > 0) {
                Set<String> keySet = paramsMap.keySet();
                Iterator it = keySet.iterator();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    String value = paramsMap.get(key);
                    nameValuePairs.add(new BasicNameValuePair(key, value));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // 执行
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                // http请求释放资源异常
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * @param url
     * @param json
     * @return
     */
    public static String postByContentTypeToJson(String url, String json) {
        String result = null;
        HttpEntity httpEntity = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建POST
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(getRequestConfig());
            // 设置头参数
            Header header = new BasicHeader("Accept-Encoding", null);
            httpPost.setHeader(header);
            // 头设置报文和通讯格式
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                // http请求释放资源异常
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * @param url
     * @param headerMap
     * @param inputStream
     * @return
     */
    public static String binaryUpload(String url, Map<String, String> headerMap, FileInputStream inputStream) {
        String result = null;
        HttpEntity httpEntity = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建POST
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(getRequestConfig());
            // 设置头参数
            Header header = new BasicHeader("Accept-Encoding", null);
            httpPost.setHeader(header);
            // 添加参数
            if (headerMap != null && headerMap.size() > 0) {
                Set<String> keySet = headerMap.keySet();
                Iterator it = keySet.iterator();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    String value = headerMap.get(key);
                    httpPost.addHeader(key, value);
                }
            }
            // 头设置报文和通讯格式
            InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream);
            httpPost.setEntity(inputStreamEntity);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                // http请求释放资源异常
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * @return
     */
    public static RequestConfig getRequestConfig() {
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(180 * 1000) // 连接超时时间
                .setConnectTimeout(180 * 1000) // 请求超时时间
                .setConnectionRequestTimeout(180 * 1000) // 连接请求超时时间
                .setRedirectsEnabled(true) // 重定向开关
                .build();
        return requestConfig;
    }

}

测试类

package com.what21.servlet.upload;

import com.what21.httpclient4.HttpClientHelperUtils;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

public class HttpClientBinaryUploadDemo {

    public static void main(String[] args) throws Exception {
        String upload = "http://localhost:9090/web/upload/binary";
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("modular", "system");
        headerMap.put("model", "org");
        headerMap.put("name", "a101.png");
        headerMap.put("type", "png");
        String file = "D:\\a101.png";
        FileInputStream inputStream = new FileInputStream(file);
        String postResultToJson = HttpClientHelperUtils.binaryUpload(upload, headerMap, inputStream);
        System.out.println(postResultToJson);
    }

}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/48368.html

(0)
上一篇 2024-04-23 19:00
下一篇 2024-04-24 10:26

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信