You've already forked FrameTour-BE
72 lines
2.5 KiB
Java
72 lines
2.5 KiB
Java
package com.ycwl.basic.aspectj;
|
|
|
|
import com.ycwl.basic.annotation.RequestToFile;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.aspectj.lang.ProceedingJoinPoint;
|
|
import org.aspectj.lang.annotation.After;
|
|
import org.aspectj.lang.annotation.Around;
|
|
import org.aspectj.lang.annotation.Aspect;
|
|
import org.aspectj.lang.annotation.Pointcut;
|
|
import org.springframework.stereotype.Component;
|
|
import org.springframework.web.context.request.RequestContextHolder;
|
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
import java.io.File;
|
|
import java.io.IOException;
|
|
import java.util.Enumeration;
|
|
import java.util.stream.Collectors;
|
|
|
|
@Aspect
|
|
@Component
|
|
@Slf4j
|
|
public class HttpSaver {
|
|
|
|
@Pointcut("@annotation(com.ycwl.basic.annotation.RequestToFile)")
|
|
public void requestToFilePointCut() {
|
|
}
|
|
|
|
@After("requestToFilePointCut()")
|
|
public void requestToFile() throws IOException {
|
|
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
|
if (attributes == null) {
|
|
return;
|
|
}
|
|
HttpServletRequest request = attributes.getRequest();
|
|
saveRequestToFile(request);
|
|
}
|
|
|
|
public static void saveRequestToFile(HttpServletRequest request) throws IOException {
|
|
StringBuilder rawReq = new StringBuilder();
|
|
rawReq.append(request.getMethod()).append(" ").append(request.getRequestURL());
|
|
String queryString = request.getQueryString();
|
|
if (queryString != null) {
|
|
rawReq.append("?").append(queryString);
|
|
}
|
|
rawReq.append("\r\n");
|
|
Enumeration<String> headerNames = request.getHeaderNames();
|
|
while (headerNames.hasMoreElements()) {
|
|
String headerName = headerNames.nextElement();
|
|
rawReq.append(headerName).append(": ").append(request.getHeader(headerName)).append("\r\n");
|
|
}
|
|
rawReq.append("\r\n");
|
|
// 获取body
|
|
try {
|
|
rawReq.append(request.getReader().lines().collect(Collectors.joining("\r\n")));
|
|
rawReq.append("\r\n");
|
|
} catch (IOException ignore) {
|
|
}
|
|
// 写入文件
|
|
File file = new File("./request/"+System.currentTimeMillis()+".http");
|
|
if (!file.getParentFile().exists()) {
|
|
file.getParentFile().mkdirs();
|
|
}
|
|
if (!file.exists()) {
|
|
file.createNewFile();
|
|
}
|
|
try (java.io.FileWriter writer = new java.io.FileWriter(file, true)) {
|
|
writer.write(rawReq.toString());
|
|
}
|
|
}
|
|
}
|