gpt4 book ai didi

Java解析HTTP文本文件格式

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:12:20 26 4
gpt4 key购买 nike

我是本周刚学的java新手,我的老师要我解析一个以文本文件格式保存的HTTP请求。基本上他要我提取
只是这一行“GET/fenway/HTTP/1.0\r\n”和这个“Host: www.redsox.com\r\n”并以文本格式保存。我的程序还不能正常工作,因为它包含错误。我所做的是逐行读取一个文本文件,然后将其输入到一个函数中,该函数尝试读取缓冲区并标记每个单词并将其保存到 copyGetWord,然后运行一个 while 循环来检测单词“GET”是否是发现它将 getWord 存储到数组列表中。

另一件事是我只允许为此使用 java,没有 perl 或 python。我也尝试过 jnetpcap 库,但在安装它们时遇到问题,所以只能使用文本文件。

希望大家帮忙。

这是一个示例文本文件:

传输控制协议(protocol),Src 端口:bridgecontrol (1073),Dst 端口:http (80),Seq:1,Ack:1,Len:270超文本传输​​协议(protocol) 获取/azur/HTTP/1.0\r\n 连接: 保持 Activity 状态\r\n 用户代理:Mozilla/4.08 [en] (WinNT; I)\r\n 主机:www.google.com\r\n

public static void main(String[] args) {

System.out.println("Tries to read the samplepcap1.txt, \n");
ReadingFile1 handle = new ReadingFile1();
ArrayList <String> StoreLine = new ArrayList<String>();

try{

FileReader ReadPcap = new FileReader("samplePcapSmall.txt");
BufferedReader bufferPcap = new BufferedReader(ReadPcap);

String readBufLine = bufferPcap.readLine();
StoreLine.add(readBufLine);

while (readBufLine!=null){
readBufLine = bufferPcap.readLine();

handle.LookForWord(readBufLine);
}

bufferPcap.close();
}
catch (FileNotFoundException e){
System.out.println("\nFile not found");
}
catch (IOException e){
System.out.println("Problem reading the file.\n");
}
}

public String LookForWord(String getWord){
ArrayList <String>MatchingWord = new ArrayList<String>();
StringTokenizer copyGetWord = new StringTokenizer(getWord," ");

while (copyGetWord.hasMoreElements()){
if(copyGetWord.nextToken().matches("GET")){
MatchingWord.add(getWord);
}
}
System.out.println("\nMatch: "+MatchingWord);

return getWord;
}

尝试读取 samplepcap1.txt,存储在 ArrayList 中并显示 ArrayList

Match: []

Match: [ GET /fenway/ HTTP/1.0\r\n]

Match: []

Match: []

Match: []
Exception in thread "main" java.lang.NullPointerException
at java.util.StringTokenizer.<init>(StringTokenizer.java:182)
at java.util.StringTokenizer.<init>(StringTokenizer.java:204)
at readingfile1.ReadingFile1.LookForWord(ReadingFile1.java:84)
at readingfile1.ReadingFile1.main(ReadingFile1.java:62)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

最佳答案

您的 while 循环是问题所在。试试这个:

String readBufLine = bufferPcap.readLine();

while (readBufLine!=null){
StoreLine.add(readBufLine);
handle.LookForWord(readBufLine);
readBufLine = bufferPcap.readLine();
}

bufferPcap.close();

这从缓冲区读取行并在读取行不为空时循环 - 新行始终作为循环主体的最后一个操作读取,以便循环的下一次迭代将检查读取行在尝试对其进行标记化之前不为空。

关于Java解析HTTP文本文件格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10348579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com