10

I am following a tutorial and also used the Stackoverflow question here. Here is my Java class:

package com.crunchify.tutorial;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import org.json.simple.JSONObject;

@Path("api")
public class CrunchifyAPI {

    @SuppressWarnings("unchecked")
    @GET
    @Path("/get")
    @Consumes(MediaType.TEXT_PLAIN)
    public String get(
            @DefaultValue("111") @QueryParam("user") int user,
            @Context UriInfo uriInfo
            ) {
        MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
        String nameParam = queryParams.getFirst("user");
        System.out.println("Data Received: " + uriInfo.getRequestUri().getQuery()
                + " | " + nameParam);
        JSONObject obj = new JSONObject();
        obj.put("auth", true);
        String ret = JSONObject.toJSONString(obj);
        return ret;
    }
}

Following is what I am GET'ing from postman:

GET>> localhost/api/get?user=123

Response is:

{"auth":true}

Server console:

Starting Crunchify's Embedded Jersey HTTPServer...

Started Crunchify's Embedded Jersey HTTPServer Successfully !!!
Data Received: ?user=123 | null
User Authenticated: true

I have tried with passing String, Integer etc but nothing works. The uri Info is getting printed correctly and the response back is also fine. The issue is that I am not getting the parameter to be read in Java Code. I will need to pass many other parameters once I am able to get this going. Please suggest. Thanks!!

Community
  • 1
  • 1
Amresh Kadian
  • 171
  • 1
  • 1
  • 11
  • I am hoping that it will print following in the server console: `Data Received: ?user=123 | 123` Similarly, later on I would like to pass String and (if possible, may be JSON). – Amresh Kadian Jan 04 '17 at 02:58

4 Answers4

5

I think you're trying too hard. As far as I can tell, doing the following should get you what you want if you call localhost/api/get?user=123:

package com.crunchify.tutorial;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import org.json.simple.JSONObject;

@Path("api")
public class CrunchifyAPI {

    @SuppressWarnings("unchecked")
    @GET
    @Path("/get")
    @Consumes(MediaType.TEXT_PLAIN)
    public String get(
            @DefaultValue("111") @QueryParam("user") Integer user,
            @Context UriInfo uriInfo
            ) {
        System.out.println("Data Received: " + uriInfo.getRequestUri().getQuery()
                + " | " + name);
        JSONObject obj = new JSONObject();
        obj.put("auth", true);
        String ret = JSONObject.toJSONString(obj);
        return ret;
    }
}

All that extra stuff with the query string isn't needed if all you need is the information passed in the user parameter.

Nielsvh
  • 1,043
  • 1
  • 19
  • 31
1

@QueryParam("user") int user

the value of that user int should be 123

See https://www.mkyong.com/webservices/jax-rs/jax-rs-queryparam-example/

Kalpesh Soni
  • 6,169
  • 2
  • 49
  • 53
  • Yes. I am expecting the following lines to display 123 instead of null: `String nameParam = queryParams.getFirst("user"); System.out.println("Data Received: " + uriInfo.getRequestUri().getQuery() + " | " + nameParam);` I have even tried changing int to String and Integer. Nothing works! – Amresh Kadian Jan 04 '17 at 03:12
  • try System.out.println(user); – Kalpesh Soni Jan 04 '17 at 03:13
  • I tried that and it prints 111 instead of null i.e. the default value. `String nameParam = queryParams.getFirst("user"); System.out.println("Data Received: " + uriInfo.getRequestUri().getQuery() + " | " + nameParam); System.out.println(user);` Result: `Data Received: ?user=aaaaa | null 111` --> should be **123** – Amresh Kadian Jan 04 '17 at 03:18
  • not sure if the issue is mixing two paradims, either use QueryParam or UriInfo, clean up your code, if needed, create two test methods See https://www.mkyong.com/webservices/jax-rs/jax-rs-queryparam-example/ – Kalpesh Soni Jan 04 '17 at 03:22
0

Well, I think you're having a problem with Java Types.

If your user is an Integer you should pass it to String first if you want to work with a String (Integer.toString() or String.valueof()).

But the way you're passing the parameter is bothering me, I'm not sure if you can pass integers by text plain medi types.

0

Query parameter mostly used in get rest api for sending data client to server . It can be optional. If it is optional then you can call you api without query parameter(path param is mandatory ) . We can send query parameter in url as

http://localhost:8080/JerseyDemo/rest/user/12?p=10

and you can retrieve this query parameter value on server side as

 @GET
    @Path("/{id}")
    public Response addUser(@PathParam("id") int id,@QueryParam("p") int page) {
        System.out.println("id=" + id+"page="+page);
        String str = "id is=" + id+"page="+page;
        return Response.status(Status.OK).entity(str).build();
   }

For more details for query parameter visit : Query Parameter Example In Jersey

Anuj Dhiman
  • 2,060
  • 1
  • 20
  • 44