【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格式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?
- 2024-05-09企业src漏洞挖掘-有意思的命令执行