gpt4 book ai didi

java - 泽西网络服务代理

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:16:01 25 4
gpt4 key购买 nike

我正在尝试实现一个 Web 服务来代理另一个我想对 API 的外部用户隐藏的服务。基本上,我想扮演中间人的角色,以便能够向隐藏的 api(即 solr)添加功能。

我必须遵循以下代码:

@POST
@Path("/update/{collection}")
public Response update(@PathParam("collection") String collection,
@Context Request request) {
//extract URL params
//update URL to target internal web service
//put body from incoming request to outgoing request
//send request and relay response back to original requestor
}

我知道我需要重写 URL 以指向内部可用的服务,添加来自 URL 或正文的参数。

这是我感到困惑的地方,我如何才能访问原始请求正文并将其传递给内部 Web 服务而不必解码内容?请求对象似乎没有给我执行这些操作的方法。

我正在寻找我应该使用的对象以及对我有帮助的潜在方法。如果有人知道我还没有真正找到任何针对类似或可移植行为的内容,我还想获得一些文档。

最佳答案

根据 JSR-311 规范的第 4.2.4 节,所有 JAX-RS 实现都必须以 byte[]、String 或 InputStream 的形式提供对请求主体的访问。

您可以使用 UriInfo 获取有关查询参数的信息。它看起来像这样:

@POST
@Path("/update/{collection}")
public Response update(@PathParam("collection") String collection, @Context UriInfo info, InputStream inputStream)
{
String fullPath = info.getAbsolutePath().toASCIIString();
System.out.println("full request path: " + fullPath);

// query params are also available from a map. query params can be repeated,
// so the Map values are actually Lists. getFirst is a convenience method
// to get the value of the first occurrence of a given query param
String foo = info.getQueryParameters().getFirst("bar");

// do the rewrite...
String newURL = SomeOtherClass.rewrite(fullPath);

// the InputStream will have the body of the request. use your favorite
// HTTP client to make the request to Solr.
String solrResponse = SomeHttpLibrary.post(newURL, inputStream);

// send the response back to the client
return Response.ok(solrResponse).build();

另一个想法。看起来您只是在重写请求并传递给 Solr。您可以通过其他几种方式执行此操作。

如果您碰巧在 Java 应用程序服务器或 Servlet 容器前面有一个 Web 服务器,您可能无需编写任何 Java 代码即可完成您的任务。除非重写条件非常复杂,否则我个人的偏好是尝试使用 Apache mod_proxy 和 mod_rewrite 执行此操作。

还有可用的 Java 库,它们将在 URL 到达应用服务器之后但在到达您的代码之前重写 URL。例如,https://code.google.com/p/urlrewritefilter/ .有了类似的东西,您只需要编写一个非常简单的方法来调用 Solr,因为 URL 会在它到达您的 REST 资源之前被重写。作为记录,我实际上还没有尝试过将那个特定的库与 Jersey 一起使用。

关于java - 泽西网络服务代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com