2013-10-25 33 views
7

我需要做一个泽西代理API服务。 我需要在球衣方法中提供完整的请求网址。 我不想指定所有可能的参数。java jersey得到完整的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 
} 

我该怎么办呢?

+0

意味着你想在这里创建一个URL?并从你想要得到param1和param2值? – Shamse

回答

10

在新泽西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(); 
} 
4

如果你需要一个智能代理,你可以得到的参数,筛选它们,并创建一个新的URL。

@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 + "&"; 
    } 

} 
+0

什么是财产? – Ricardo

+0

更新了代码。当然应该使用“钥匙”。看起来我没有设法清理从我的项目中获取的代码。 – Azee

0

尝试UriInfo uriInfo,

@POST 
    @Consumes({ MediaType.APPLICATION_JSON}) 
    @Produces({ MediaType.APPLICATION_JSON}) 
    @Path("add") 
    public Response addSuggestionAndFeedback(@Context UriInfo uriInfo, Student student) { 

      System.out.println(uriInfo.getAbsolutePath()); 

     ......... 
    } 

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

你可以试试下面的选项也

enter image description here

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配置类

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"); 

    } 

}