工具类代码整理

HttpClient

1、HttpClient详细使用示例

# 参数列表 byte[] pdfFile,

MultipartFile file = new MockMultipartFile("file", "hello-" + number + ".pdf", "application/pdf", pdfFile);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setContentType(ContentType.MULTIPART_FORM_DATA);

ContentType fileContentType = ContentType.create(ContentType.parse("application/pdf").getMimeType(), StandardCharsets.UTF_8);
builder.addBinaryBody("file",pdfFile,fileContentType, URLEncoder.encode(file.getOriginalFilename(), "utf-8"));    

发送文件示例图
在这里插入图片描述
中文问题:

  1. 防止服务端收到的文件名乱码。 先将文件名URLEncode,然后服务端拿到文件名时在URLDecode。就能避免乱码问题。
    可查看发送文件示例

  2. RFC6532

    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); 
    
  3. 其他方式

public class EsignUtils {

    public static MultipartFile createFileItem(InputStream inputStream, String fileName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "file";
        FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
        int bytesRead;
        byte[] buffer = new byte[10 * 1024 * 1024];
        //使用输出流输出输入流的字节
        try (OutputStream os = item.getOutputStream()) {
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (IOException e) {
            //logger.error("Stream copy exception", e);
            throw new IllegalArgumentException("文件上传失败");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //logger.error("Stream close exception", e);
                }
            }
        }
        return new CommonsMultipartFile(item);

    }
}

  @PostMapping(value = "XXX", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    ResponseEntity<HashMap<String, String>> generateSignatureFile(@PathVariable("organizationId") Long organizationId, @RequestPart("file") MultipartFile multipartFile, @RequestParam(value = "from", required = false) String from);


    @ApiOperation(value = "生成签署文件")
    @Permission(level = ResourceLevel.ORGANIZATION)
    @PostMapping("/XXX")
    public ResponseEntity<HashMap<String, String>> generateSignatureFile(@PathVariable("organizationId") Long organizationId,
                                                                         @RequestParam("file") MultipartFile multipartFile,
                                                                         @RequestParam(value = "from", required = false) String from) {
        return Results.success(this.esignService.generateSignatureFile(multipartFile, from));
    }

其他:
在这里插入图片描述
这种代码如下:

List<BasicNameValuePair> paramsPair=new ArrayList<>();
String jsonParams= JsonUtil.toString(yoZoOpenDTO);
paramsPair.add(new BasicNameValuePair("jsonParams",jsonParams));
UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(paramsPair);

String result = HttpPostUtil.postFile("http://xxxxx/api.do",formEntity,"UTF-8");

public class HttpPostUtil {

    public static String postFile(String url, HttpEntity requestEntity, String encoding) {
        try{
            String body = "";
            //创建httpclient对象
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            //设置请求参数
            httpPost.setEntity(requestEntity);
            //执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = httpClient.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            System.out.println(body);
            EntityUtils.consume(entity);
            //释放链接
            response.close();
            return body;
        }catch (Exception e){
            throw new CommonException("请求失败");
        }
    }
}

List分割工具类

  1. averageAssign 平均分割
  2. splitList 按照指定长度分割
public class ListSplitUtil {
    /**
     * @param list
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> list, int n){
        List<List<T>> result=new ArrayList<List<T>>();
        int remaider=list.size()%n;  //(先计算出余数)
        int number=list.size()/n;  //然后是商
        int offset=0;//偏移量
        for(int i=0;i<n;i++){
            List<T> value=null;
            if(remaider>0){
                value=list.subList(i*number+offset, (i+1)*number+offset+1);
                remaider--;
                offset++;
            }else{
                value=list.subList(i*number+offset, (i+1)*number+offset);
            }
            result.add(value);
        }
        return result;
    }
    /**
     * @param list
     * @param len
     * @return
     */
    public static<T> List<List<T>> splitList(List<T> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return null;
        }
        List<List<T>> result = new ArrayList<List<T>>();
        int size = list.size();
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<T> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
            result.add(subList);
        }
        return result;
    }
}

图片转PDF,PDF转图片

图片转PDF

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.4.2</version>
</dependency>
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Image2PDF {
    /*** @param picturePath 图片地址*/
    private static void createPic(Document document, String picturePath) {
        try {
            Image image = Image.getInstance(picturePath);
            float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
            float documentHeight = documentWidth / 580 * 400;//重新设置宽高
            image.scaleAbsolute(documentWidth, documentHeight);//重新设置宽高
            document.add(image);
        } catch (Exception ex) {
        }
    }
    public static void image2pdf(String text, String pdf) throws DocumentException, IOException {
        Document document = new Document();
        OutputStream os = new FileOutputStream(new File(pdf));
        PdfWriter.getInstance(document,os);
        document.open();
        createPic(document,text);
        document.close();
    }
    public static void main(String[] args) throws IOException, DocumentException {
        image2pdf("C:\\Users\\Administrator\\Desktop\\8.jpg","C:\\Users\\Administrator\\Desktop\\111.pdf");
    }
}

PDF转图片

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>fontbox</artifactId>
    <version>2.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.1</version>
</dependency>
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class PDFConvert {

    /**
     * PDF转图片的流
     */
    public static List<byte[]> PDF2JPG(InputStream inputStream) throws IOException {
        List<byte[]> imageData=new ArrayList<>();
        OutputStream out = null;
        if (inputStream==null) {
            throw new FileNotFoundException();
        } else {
            ByteArrayOutputStream bos = null;
            BufferedInputStream in = null;
            PDDocument doc = null;

            try {
                in = new BufferedInputStream(inputStream);
                doc = PDDocument.load(in);

                PDFRenderer pdfRenderer = new PDFRenderer(doc);
                PDPageTree pages = doc.getPages();
                int pageCount = pages.getCount();
                for (int i = 0; i < pageCount; i++) {
                    BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
                    bos = new ByteArrayOutputStream();
                    ImageIO.write(bim, "jpg", bos);
                    byte[] var7 = bos.toByteArray();
                    imageData.add(var7);
                }

//                //jpg文件转出路径
//                out = new FileOutputStream("D:\\abc.jpg");
//                out.write(bos.toByteArray());
                return imageData;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }
                bos.close();
            }
        }
    }
}

swagger文档导出接口文档

https://tools.kalvinbg.cn/dev/swagger2word
https://blog.csdn.net/mangomango123/article/details/134399323

查询出List<HashMap<String, String>>,转HashMap<String, String>

# 查询出List<HashMap<String, String>>
List<HashMap<String, String>> syncErrorCodeAndCount = dataSyncMapper.selectErrorData(preDate, nowDate);

# Mapper
List<HashMap<String, String>> selectErrorData(@Param("from") Date preDate, @Param("to") Date nowDate);

# XML
<select id="selectErrorData" resultType="java.util.HashMap">
    SELECT
        hs.syncer_code,
        COUNT(*) AS count
    FROM
        XXXXXX
</select>

# 转为HashMap
HashMap<String, String> mergeMap = mergeMaps(syncErrorCodeAndCount);

public static HashMap<String, String> mergeMaps(List<HashMap<String, String>> listOfMaps) {
    HashMap<String, String> mergedMap = new HashMap<>();
    for (HashMap<String, String> map : listOfMaps) {
        mergedMap.put(map.get("syncer_code"),map.get("count"));
    }
    return mergedMap;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值