使用 restlet 在 Chrome 中返回获取响应时出现文档为空错误

Document is empty error while returning get response in Chrome using restlet

我刚刚开始使用 restlet 框架。 我已经编写了简单的服务器和资源 类 来开始。这是代码:

资源:

import org.restlet.resource.Get; 
import org.restlet.resource.ServerResource; 

public class HelloWorldResource extends ServerResource { 
    @Get 
    public String represent(){ 
            return "Hello World"; 
    } 
}

服务器:

import org.restlet.Server; 
import org.restlet.data.Protocol; 

public class HelloWorldServer { 
    public static void main(String[] args) throws Exception { 
            Server server = new Server(Protocol.HTTP, 8989, HelloWorldResource.class); 
            server.start(); 
    } 
} 

当我尝试通过点击 http://localhost:8989/ 运行 Chrome 中的代码时,出现以下错误:

当我将资源 return 值包含在 xml 标签中时,此错误消失 <tag>Hello World</tag> 并且默认 XML 模板显示在 Chrome 在标签中使用 "Hello World"。

使用 ClientResource 变量通过代码访问资源在没有标签的情况下也能正常工作。

此外,当 运行在 IE 中使用相同的代码时,它会自动将包含消息的 JSON 文件下载到我的计算机。

这种行为背后的原因是什么?

谢谢。

服务器 returns 一个 XML 文档,其格式不正确。您需要在其中包含根元素,而不是纯文本。

实际上,您的问题与HTTP (Conneg) 的内容协商特性有关。这利用了两个 headers:

  • Content-Type:请求或响应的文本负载格式。在你的例子中,这个 header 告诉客户你 return.
  • 的数据结构
  • Accept:您期望在响应中的文本有效负载的格式。此 header 在请求中使用,并由浏览器根据其支持自动设置。服务器负责考虑这个header到return支持的内容。

有关详细信息,请参阅本文:

Restlet 提供开箱即用的内容协商。我的意思是你 return 一个文本,它会自动设置 Content-Type header 在响应 text/plain:

@Get 
public String represent(){ 
  return "Hello World"; 
}

如果您想要 return 另一种内容类型,您完全有办法。这是一个示例:

@Get 
public Representation represent() { 
  return new StringRepresentation(
     "<tag>Hello World</tag>",
     MediaType.APPLICATION_XML); 
}

您还可以在 @Get 级别定义参数以考虑提供的 Accept header:

@Get('xml')
public Representation represent() { 
  return new StringRepresentation(
     "<tag>Hello World</tag>",
     MediaType.APPLICATION_XML); 
}

@Get('json')
public Representation represent() { 
  return new StringRepresentation(
     "{ \"message\": \"Hello World\" }",
     MediaType.APPLICATION_JSON); 
}

// By default - if nothing matches above
@Get
public Representation represent() { 
  return new StringRepresentation(
     "Hello World",
     MediaType.PLAIN_TEXT); 
}

另一件事是 Restlet 允许在服务器资源方法级别直接利用 bean,而不是 StringRepresentation。这对应于转换器功能。要使用它,您需要注册一个转换器。例如,只需添加来自 Restlet 的 Jackson 扩展的 jar 文件(org.restlet.ext.jackson 具有依赖项)。基于 Jackson 的转换器将自动注册。这样文本有效负载将转换为 bean 和 bean 为文本。

现在您可以使用类似的东西了:

@Get('json')
public Message represent() { 
  Message message = new Message();
  message.setMessage("Hello world");
  return message; 
}

基于您创建的 Message class:

public class Message {
  private String message;

  public String getMessage() { return this.message; }
  public void setMessage(String message) { this.message = message; }
}