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

2022/4/3 11:49:31

本文主要是介绍【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;

/**
 * <dependency>
 * <groupId>com.alibaba</groupId>
 * <artifactId>fastjson</artifactId>
 * <version>1.2.58</version>
 * </dependency>
 */
public class AnalysisHeader {
    /**
     * 读取文本文件
     *
     * @param filePath 文件路径
     * @return 返回读取到的每行 列表
     */
    public static ArrayList<String> readFile(String filePath) {
        ArrayList<String> 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<String> 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));
    }
}

 

三、解析效果

 



这篇关于【Java】解析浏览器中的header请求头为JSON格式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程