Restlet 重用 InputStream [英] Restlet reuse InputStream

查看:48
本文介绍了Restlet 重用 InputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下一个代码.

过滤器:

public class InputFilter extends Filter {

  @Override
  protected int beforeHandle(Request request, Response response) {

    int result = CONTINUE;
    InputStream inputStream = request.getEntity().getStream();
    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");

    String theString = writer.toString();
    JsonRepresentation jRep = new JsonRepresentation(theString);

    String token = jRep.getJsonObject().getString("token");
    .
    .
    .
    return result;
  }
}

资源:

public class inputResource extends GsServerResource {

  @Post
  public JsonRepresentation getInput(JsonRepresentation jRep) {
    String token = jRep.getJsonObject().getString("token");
    .
    .
    .
  }
}

jRep 为 NULL.

jRep is NULL.

我在过滤器中使用了一次流,由于它不是transient,因此它被关闭以备后用.

I use the stream once in the filter and it is closed for later use due to the fact that it is not transient.

我目前的修复:

在过滤器中(检索流后):

in the filter (after retrieving the Stream):

request.getAttributes().putIfAbsent("token", token);

在资源中:

String token = (String) getRequest().getAttributes().get("token");

除了将数据放入 filter 中的 context 并稍后在 resource 中检索它之外,还有其他解决方案吗?

Is there any other solution than putting the data in to the context in the filter and later retrieving it in the resource?

推荐答案

事实上,您可以根据您提取的实体文本,根据 StringRepresentation 在过滤器中再次设置请求的实体来自请求,如下所述:

In fact, you can set again within the filter the entity for the request based on a StringRepresentation based on the entity text you extracted from the request, as described below:

// Get entity text
Representation repr = request.getEntity();
String content = repr.getText();

// Use entity text
InputStream inputStream = request.getEntity().getStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");

String theString = writer.toString();
JsonRepresentation jRep = new JsonRepresentation(theString);

String token = jRep.getJsonObject().getString("token");

// Set again the entity for the request
StringRepresentation sRepr = new StringRepresentation(
                           content, repr.getMediaType());
request.setEntity(sRepr);

使用这种方法,您可以再次读取过滤器后面资源中的请求实体.

Using this approach, you can read again the request entity within the resource behind the filter.

希望对你有帮助蒂埃里

这篇关于Restlet 重用 InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆