tio-boot 输出请求信息

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

通过上述代码和示例,我们可以轻松地在控制台输出客户端请求的详细信息,便于调试和分析。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值