Skip to content

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

@hstan92

Description

@hstan92

类似于 #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()呢?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions