package com.engine.htxc.commonutil.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author xf
 * @version 1.0.0
 * @ClassName RequestJSsonUtil.java
 * @createTime 2021年11月30日 16:18:00
 */
public class RequestJsonUtil {

    public static JSONObject getRequestJsonObject(HttpServletRequest req) throws IOException {
            String value = getRequestJsonString(req);
            return JSONObject.parseObject(value);
        }

    public static JSONArray getRequestJsonArrray(HttpServletRequest req) throws IOException {
        String value = getRequestJsonString(req);
        return JSONArray.parseArray(value);
    }

        public static String getRequestJsonString(HttpServletRequest req) throws IOException {
            String value = req.getMethod();
            return value.equals("GET") ? (new String(req.getQueryString().getBytes("iso-8859-1"), "utf-8")).replaceAll("%22", "\"") : getRequestPostStr(req);
        }

        public static byte[] getRequestPostBytes(HttpServletRequest req) throws IOException {
            int lenth = req.getContentLength();
            if (lenth < 0) {
                return null;
            } else {
                byte[] bytes = new byte[lenth];

                int count;
                for(int i = 0; i < lenth; i += count) {
                    count = req.getInputStream().read(bytes, i, lenth - i);
                    if (count == -1) {
                        break;
                    }
                }

                return bytes;
            }
        }

        public static String getRequestPostStr(HttpServletRequest req) throws IOException {
            byte[] value = getRequestPostBytes(req);
            String encoding = req.getCharacterEncoding();
            if (encoding == null) {
                encoding = "UTF-8";
            }

            return new String(value, encoding);
        }


}
