package com.gic.haoban.manage.web.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Author guojx
 * @Date 2024/1/4 16:05
 */
@Slf4j
public class RequestParamUtils {

    public static boolean isJson(String params) {
        try {
            JSONObject.parseObject(params);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String getJsonParam(HttpServletRequest request) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } catch (IOException ex) {
            log.warn("获取JSON参数错误:{}", ex.getMessage(), ex);
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    log.warn("关闭读取流错误:{}", ex.getMessage(), ex);
                }
            }
        }
        return stringBuilder.toString();
    }
}
