tio-boot 输出请求信息
转载自https://tio-boot.litongjava.com/zh/05_web%E5%BC%80%E5%8F%91/23.html
在一些情况下,我们可能需要查看客户端的请求信息,包括请求头、请求体等。我们可以使用以下代码将这些信息打印到控制台:
示例代码
import java.util.Map;
import com.litongjava.tio.boot.http.TioControllerContext;
import com.litongjava.tio.http.common.HttpRequest;
import com.litongjava.tio.http.common.HttpResponse;
import com.litongjava.tio.http.common.RequestLine;
public class IndexRequestHandler {
public HttpResponse index(HttpRequest httpRequest) {
HttpResponse response = TioControllerContext.getResponse();
StringBuffer requestString = printRequest(httpRequest);
response.setBody(requestString.toString().getBytes());
return response;
}
private StringBuffer printRequest(HttpRequest httpRequest) {
StringBuffer stringBuffer = new StringBuffer();
RequestLine requestLine = httpRequest.getRequestLine();
stringBuffer.append(requestLine.toString()).append("\n");
// 打印请求头信息
Map<String, String> headers = httpRequest.getHeaders();
for (Map.Entry<String, String> e : headers.entrySet()) {
stringBuffer.append(e.getKey() + ": " + e.getValue()).append("\n");
}
// 根据Content-Type打印请求体信息
String contentType = httpRequest.getContentType();
if (contentType != null && contentType.startsWith("application/json")) {
stringBuffer.append(httpRequest.getBodyString());
} else {
Map<String, Object[]> params = httpRequest.getParams();
for (Map.Entry<String, Object[]> e : params.entrySet()) {
stringBuffer.append(e.getKey() + ": " + e.getValue()[0]).append("\n");
}
}
// 输出到控制台
System.out.println(stringBuffer.toString());
return stringBuffer;
}
}
输出信息示例
示例 1:JSON 格式的请求体
请求信息:
POST /hi?text=how%20are%20you? HTTP/1.1
content-length:23
host:localhost
content-type:application/json
connection:keep-alive
accept-encoding:gzip, deflate, br
accept:*/*
{
"key":"value"
}
示例 2:表单格式的请求体
请求信息:
POST /hi?text=how%20are%20you? HTTP/1.1
content-length:9
host:localhost
connection:keep-alive
content-type:application/x-www-form-urlencoded
accept-encoding:gzip, deflate, br
accept:*/*
text:how are you?
key:value
通过上述代码和示例,我们可以轻松地在控制台输出客户端请求的详细信息,便于调试和分析。