Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HttpRequest.getBody().string() 只可以被读一次? #560

Open
hstan92 opened this issue Nov 29, 2024 · 0 comments
Open

HttpRequest.getBody().string() 只可以被读一次? #560

hstan92 opened this issue Nov 29, 2024 · 0 comments

Comments

@hstan92
Copy link

hstan92 commented Nov 29, 2024

类似于 #469

用着 v2.1.12 版本

我发现 HttpRequest.getBody().string() 好像只可以被读一次,想问这是原本的设计还是 bug 呢?

假设我有一个 Interceptor 里头 call 了 body.string()

@Interceptor
public class LoggerInterceptor implements HandlerInterceptor {
    private static final String TAG = "w_interceptor";

    @Override
    public boolean onIntercept(@NonNull HttpRequest request, @NonNull HttpResponse response,
                               @NonNull RequestHandler handler) {
        RequestBody body = request.getBody();
        try {
            if (body != null) {
                String _body = body.string();  // 第一次读取, 不会 empty string
                Log.d(TAG, "Body: " + _body);
            }
        } catch (IOException e) {
            Log.e(TAG, "onIntercept: ", e);
        }
        return false;
    }
}

我之后的 controller 再 call body.string() 就会 null

@RestController
@RequestMapping(path = "/api")
public class RouterController {
    @PostMapping(path = "/execute")
    public StringBody showPage(HttpRequest request, @Nullable RequestBody body) throws IOException {
        String bodyContent = body.string();   // 永远都拿到 empty string
        Log.d(TAG, "showPage: body = " + bodyContent); // bodyContent 是 empty string
    }
}

我如果移除掉我的 LoggerInterceptor class 或者不在里头 call body.string(), 我的 RouterController 里头第一次 call 的 body.string() 就不会 empty string 了.

问:有没有别的办法可以在 LoggerInterceptor 和 我的 RouterController 里头都 call body.string()呢?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant