java jersey获取完整的URL

时间:2013-10-25 12:02:26

标签: java url jersey

我需要为Jersey做一个代理API服务。 我需要在泽西方法中拥有完整的请求URL。 我不想指定所有可能的参数。

例如:

@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/media.json")
public  String getMedia( ){
    // here I want to get the full request URL like /media.json?param1=value1&param2=value2
}

我该怎么做?

4 个答案:

答案 0 :(得分:13)

在Jersey 2.x中(注意它使用HttpServletRequest对象):

@GET
@Path("/test")
public Response test(@Context HttpServletRequest request) {
    String url = request.getRequestURL().toString();
    String query = request.getQueryString();
    String reqString = url + " + " + query;
    return Response.status(Status.OK).entity(reqString).build();
}

答案 1 :(得分:4)

如果您需要智能代理,您可以获取参数,过滤它们并创建新网址。

@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/media.json")
public  String getMedia(@Context HttpServletRequest hsr){
    Enumeration parameters = hsr.getParameterNames();
    while (parameters.hasMoreElements()) {
        String key = (String) parameters.nextElement();
        String value = hsr.getParameter(key);
    //Here you can add values to a new string: key + "=" + value + "&"; 
    }

}

答案 2 :(得分:3)

尝试UriInfo,如下,

final KeyStore store = KeyStore.getInstance("PKCS12");

try (FileInputStream stream = new FileInputStream(new File("file.pfx"))) {
    store.load(stream, PASS.toCharArray());
}
SSLContext sslContext = SSLContexts.custom()
    .loadKeyMaterial(store, PASS.toCharArray())
    .loadTrustMaterial(store, TrustSelfSignedStrategy.INSTANCE)
    .build();

OUT PUT: - https://localhost:9091/api/suggestionandfeedback/add

您也可以尝试以下选项

enter image description here

答案 3 :(得分:0)

你可以使用泽西过滤器。

public class HTTPFilter implements ContainerRequestFilter {

private static final Logger logger = LoggerFactory.getLogger(HTTPFilter.class);

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {

        logger.info(containerRequestContext.getUriInfo().getPath() + " endpoint called...");
        //logger.info(containerRequestContext.getUriInfo().getAbsolutePath() + " endpoint called...");

    }
}

之后你必须在http配置文件中注册它或者只是扩展ResourceConfig类。这是你如何在http config class

中注册它
public class HTTPServer {

    public static final Logger logger = LoggerFactory.getLogger(HTTPServer.class);

    public static void init() {

        URI baseUri = UriBuilder.fromUri("http://localhost/").port(9191).build();
        ResourceConfig config = new ResourceConfig(Endpoints.class, HTTPFilter.class);
        HttpServer server = JdkHttpServerFactory.createHttpServer(baseUri, config);

        logger.info("HTTP Server started");

    }

}