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

cn.patterncat.tracing.helper.HttpBodyTraceHelper Maven / Gradle / Ivy

The newest version!
package cn.patterncat.tracing.helper;

import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by cat on 2018-12-04.
 */
public class HttpBodyTraceHelper {

    public static final int MAX_PRINT_BODY_PAYLOAD_BYTES = 2048;

    public static boolean isContentTypePrintable(List printableMediaSubTypes,MediaType contentType) {
        if (contentType != null && printableMediaSubTypes != null) {
            return printableMediaSubTypes.contains(contentType.getSubtype());
        }
        return false;
    }

    public static boolean isContentTypePrintable(List printableMediaSubTypes,String contentTypeStr) {
        if(StringUtils.isEmpty(contentTypeStr) || printableMediaSubTypes == null){
            return false;
        }
        try{
            //NOTE 这个估计有点耗时
            MediaType mediaType = MediaType.parseMediaType(contentTypeStr);
            if (mediaType != null) {
                return printableMediaSubTypes.contains(mediaType.getSubtype());
            }
        }catch (Exception e){
            //ignore
        }
        return false;
    }

    public static String getContentAsString(byte[] buf, int maxLength, String charsetName) {
        if (buf == null || buf.length == 0) return "";
        int length = Math.min(buf.length, maxLength > 0 ? maxLength : MAX_PRINT_BODY_PAYLOAD_BYTES);
        try {
            return new String(buf, 0, length, charsetName);
        } catch (UnsupportedEncodingException ex) {
            return "Unsupported Encoding";
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy