Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Rest - send parametrized List using GET method

I am trying to send a List by GET method.

Here is my Server side:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers(){
    return managment.getUsers();
}

And my client side:

public static void getUsers(){
    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/Serwer07/user");

        ClientResponse response = webResource.accept("application/json")
                .get(ClientResponse.class);

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }

       List users = response.getEntity(List.class);          
       User user = (User) users.get(0);  //cannot cast
        e.printStackTrace();
    }
}

I have problem with cast from Java Object to User. How can I send this List ?

Thanks in advance.

like image 983
javaGirl Avatar asked Jul 18 '12 19:07

javaGirl


People also ask

Can we send parameters in GET request?

Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters. Let's go through an example to understand it further.

Can we pass body parameter in Get method?

So, yes, you can send a body with GET, and no, it is never useful to do so. This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress). Yes, you can send a request body with GET but it should not have any meaning.

How do you pass parameters in GET request URL response?

Using React Router, when you want to create a Route that uses a URL parameter, you do so by including a : in front of the value you pass to Route 's path prop. Finally, to access the value of the URL parameter from inside of the component that is rendered by React Router, you can use React Router's useParams Hook.


1 Answers

Use GenericType.

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

UPDATE

ClientResponse also overloads getEntity to accept GenericTypes.

List<User> users = response.getEntity(new GenericType<List<User>>() {});      
like image 66
Anthony Accioly Avatar answered Oct 18 '22 12:10

Anthony Accioly