java - JAX-RS 消耗资源对象

标签 java rest jersey jax-rs marshalling

JAX-RS 的 Jersey 实现的服务。我的问题是是否可以直接使用 URI 表示的对象。如果我的措辞有误,我很抱歉,但在 Web 服务、REST 和编码/解码方面,我是一个初学者。

为了说明我的问题,我制作了一个示例网络服务。 首先,我创建了一个将由网络服务发布和使用的 POJO

package com.test.webapp.resources;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class SomeData {

    private String name;
    private String id;
    private String description;

    public SomeData() {

    }

    public SomeData(String id, String name, String description) {

        this.id = id;
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public String getId() {
        return id;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {

        return "SomeData [id=" 
               + id 
               + ", name=" 
               + name 
               + ", description=" 
               + description + "]";
    }
}

接下来将发布数据的网络服务:

package com.test.webapp.resources;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

@Path("/data")
public class DataResource {

    @Context
    private UriInfo uriInfo;
    @Context
    private Request request;

    private static SomeData firstData = new SomeData("1", 
                                                     "Important Data", 
                                                     "First Test Data");
    private static SomeData secondData = new SomeData("2", 
                                                      "Very Important Data", 
                                                      "Second Test Data");
    private static SomeData thirdData = new SomeData("3",  
                                                     "Some Data", 
                                                     "Third Test Data");    
    private static List<SomeData> someDataList = new ArrayList<>();

    static {

        someDataList.add(firstData);
        someDataList.add(secondData);
        someDataList.add(thirdData);        
    }

    @GET
    @Path("/someData/list")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public List<SomeData> getSomeData() {

        return someDataList; 
    }

    @GET
    @Path("/someData/{id}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public SomeData getSomeDataSingle(@PathParam("id") int id) {

        try {

            SomeData data = someDataList.get(id);

            return new SomeData(data.getId(), 
                                       data.getName(), 
                                       data.getDescription());
        }           
        catch (IndexOutOfBoundsException e){

            throw new RuntimeException("Data with id: " 
                                       + id + " was not found");
        }
    }   


    @POST
    @Path("/someSummary/create/all/uri")
    @Consumes(MediaType.APPLICATION_XML)
    public Response createSumaryFromUrl(String someDataResourceString) {

        URI someDataResource = null;

        try {

            someDataResource = new URI(someDataResourceString);
        } 
        catch (URISyntaxException e1) {

            e1.printStackTrace();
        }

        List<SomeData> theDataList = this.comsumeData(someDataResource);

        String summaryString = "";

        for(SomeData data : theDataList) {

            summaryString += data.getDescription() + " ";
        }

        return Response.status(201).entity(summaryString).build();
    }

    private List<SomeData> comsumeData(URI someDataResource) {

        ClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures()
                    .put(JSONConfiguration.FEATURE_POJO_MAPPING, 
                         Boolean.TRUE);
        Client client = Client.create(clientConfig);
        WebResource webResource = client.resource(someDataResource);

        List<SomeData> dataListFromGet = webResource
                                  .accept(MediaType.APPLICATION_JSON)                                                                            
                                  .get(new GenericType<List<SomeData>>(){});

        return dataListFromGet;

    }
}

现在我创建一个 Jersey 客户端来发布帖子并创建摘要。

package com.test.webapp.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class JerseyClient {

    public static void main(String[] args) {

        try {

            ClientConfig clientConfig = new DefaultClientConfig();
            clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
            Client client = Client.create(clientConfig);
            WebResource webResource = client.resource("http://localhost:8080/WebApp");

            URI someDataListResource = new URI("http://localhost:8080/WebApp/data/someData/list");

            ClientResponse response = webResource
                    .path("data/someSummary/create/all/uri")
                    .accept(MediaType.APPLICATION_XML)
                    .type(MediaType.APPLICATION_XML)
                    .post(ClientResponse.class, someDataListResource.toString());

            if(response.getStatus() != 201) {

                throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
            }

            System.out.println(response.getEntity(String.class));
        }

        catch(Exception e) {

            e.printStackTrace();
        }
    }
}

所以这一切都很好。不过,我认为这是在 Web 服务内创建客户端来消耗资源的某种解决方法。我想要做的就是在网络服务中一起删除客户端并直接使用资源后面的对象。

类似这样的事情:

在网络服务中:

@POST
@Path("/someSummary/create/all")
@Consumes(MediaType.APPLICATION_XML)
public Response createSumary(List<SomeData> someDataList) {

    String summaryString = "";

    for(SomeData data : someDataList) {

        summaryString += data.getDescription() + " ";
    }   

    return Response.status(201).entity(summaryString).build();
}

在客户端中是这样的:

URI someDataListResource = new URI("http://localhost:8080/WebApp/data/someData/list");

ClientResponse response = webResource
        .path("data/someSummary/create/all/uri")
        .accept(MediaType.APPLICATION_XML)
        .type(MediaType.APPLICATION_XML)
        .post(ClientResponse.class, someDataListResource);

这可能吗,还是我弄错了?

很抱歉,如果这是一个微不足道的问题,但我做了一些研究,但找不到任何东西,可能是因为我的搜索规则由于我的经验不足而错误。

感谢您提前做出的努力。

最佳答案

首先,是的,如果您想使用 URI,则需要手动完成。您可以编写这样的自定义类:

public class SomeDataList extends ArrayList<SomeData> {
   public static SomeDataList valueOf(String uri) {
       // fetch the URI & create the list with the objects, return it.
   }
   // other methods
}

只需在您的请求中使用这个特定的类即可:

@POST
@Path("/someSummary/create/all/uri")
@Consumes(MediaType.APPLICATION_XML)
public Response createSumaryFromUrl(@QueryParam("uri") SomeDataList someDataResourceString) {
   //....
}

但是,在我看来,您想要检索的特定对象已经在服务器中,因此无需通过 HTTP+REST 进行往返 - 只需直接找到它们即可。

关于java - JAX-RS 消耗资源对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22410381/

相关文章:

java - 为什么这段代码没有画线?

java - 相同的代码在 C 和 Java 中给出了不同的答案,你能帮我吗?

java - POST 到 Jersey REST 服务时出现错误 415 不支持的媒体类型

tomcat - Jersey 支持 CORS 吗?

java - 无法从 Rest 方法发送响应

java - 每个测试用例的代码覆盖率库

java - 我如何访问我从另一个类返回的嵌套 HashMap 值? java

rest - 我可以在 CREATE 或 SET 上参数化标签和属性吗? (REST 和交易)

Java:在 Restful 服务中创建包含多个值的 JSON 响应

java - Spring Boot 异常处理程序不捕获异常