【Java】解析浏览器中的header请求头为JSON格式


一、header文件

把浏览器中的header复制到文件中

二、代码解析

备注:可直接复制使用

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * 
 * com.alibaba
 * fastjson
 * 1.2.58
 * 
 */
public class AnalysisHeader {
    /**
     * 读取文本文件
     *
     * @param filePath 文件路径
     * @return 返回读取到的每行 列表
     */
    public static ArrayList readFile(String filePath) {
        ArrayList resultData = new ArrayList<>();
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(new FileInputStream(new File(filePath)), "UTF-8")
            );
            String lineTxt = null;
            int count = 0;
            // 逐行读取
            while ((lineTxt = br.readLine()) != null) {
                // 输出内容到控制台
                resultData.add(lineTxt);
                count++;
            }
            br.close();
        } catch (Exception e) {
            System.out.println("Error Message :" + e);
        }
        return resultData;
    }

    /**
     * 格式化JSON
     *
     * @param jsonObject JSON对象
     * @return 返回格式化后的JSON字符串
     */
    public static String formatJson(JSONObject jsonObject) {
        return JSON.toJSONString(
                jsonObject,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat
        );
    }

    /**
     * 解析Header文件
     *
     * @param headerPath
     * @return
     */
    public static String analysis(String headerPath) {
        ArrayList headers = AnalysisHeader.readFile(headerPath);
        JSONObject headerJson = new JSONObject();
        for (String header : headers) {
            String[] split = header.split(": ");
            headerJson.put(split[0], split[1]);
        }
        return AnalysisHeader.formatJson(headerJson);
    }

    public static void main(String[] args) {
        String filePath = "C:\\Users\\Desktop\\header.txt";
        System.out.println(AnalysisHeader.analysis(filePath));
    }
}

三、解析效果