HttpServletRequest转string
时间: 2023-10-08 19:12:11 浏览: 107
可以使用以下代码将HttpServletRequest对象转换为字符串:
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
public class RequestUtils {
public static String convertToString(HttpServletRequest request) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append(request.getMethod()).append(" ").append(request.getRequestURI());
String queryString = request.getQueryString();
if (queryString != null) {
sb.append("?").append(queryString);
}
sb.append("\n");
// Append headers
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
sb.append(headerName).append(": ").append(headerValue).append("\n");
}
sb.append("\n");
// Append body
String requestBody = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
sb.append(requestBody);
return sb.toString();
}
// Example usage
public void exampleUsage(HttpServletRequest request, HttpServletResponse response) throws IOException {
String requestString = convertToString(request);
PrintWriter out = response.getWriter();
out.println(requestString);
}
}
```
阅读全文