Added parsing of HTTP requests from file

This commit is contained in:
SearchNull
2021-12-28 23:54:37 +08:00
parent a6a0aa4bfc
commit dc83331954

View File

@@ -1,5 +1,7 @@
package io.github.exp1orer.util;
import io.github.exp1orer.StartUp;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
@@ -79,10 +81,10 @@ public class HttpUtil {
conn.setRequestProperty(key, headers.get(key));
}
}
if (method.equalsIgnoreCase("GET")) {
if ("GET".equalsIgnoreCase(method)) {
conn.setRequestMethod(method);
conn.connect();
} else if (method.equalsIgnoreCase("POST")) {
} else if ("POST".equalsIgnoreCase(method)) {
conn.setDoOutput(true);
if (body != null) {
OutputStream os = conn.getOutputStream();
@@ -123,6 +125,60 @@ public class HttpUtil {
return sb.toString();
}
public static boolean formatHttp(String file) throws IOException {
String line, host, key, value, uri = "", url = "", method = "GET";
StringBuffer body = new StringBuffer();
String protocol = "http";
boolean httpRequestFlag = false, httpBody = false;
Map<String, String> headers = new HashMap<>();
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
if (!httpRequestFlag) {
method = line.split(" ")[0];
if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) {
System.out.println("请检查文件内容是否为HTTP请求!");
System.exit(1);
}
httpRequestFlag = true;
uri = line.split(" ")[1].trim();
continue;
}
if (line.startsWith("Host")) {
host = line.split(":")[1].trim();
if (host.startsWith("https://")) {
protocol = "https";
}
url = String.format("%s://%s%s", protocol, host, uri);
continue;
}
// 处理请求头
if (line.split(":").length >= 2) {
key = line.substring(0, line.indexOf(":") - 1).trim();
value = line.substring(line.indexOf(":") + 1).trim();
headers.put(key, value);
continue;
}
if ("".equals(line)) {
httpBody = true;
}
if (httpBody && !"".equals(line)) {
body.append(line);
}
}
StartUp.method = method;
StartUp.url = url;
StartUp.headers = headers;
StartUp.body = body.toString();
return true;
}
public static String normalzedUrl(String url) throws Exception {
Map<String, String> parameter = new HashMap<String, String>();
URI uri = new URI(url);