Passing JSONObject in RestFul Webservice - java

I am using RestFul Webservice with JBoss Server to deploy the app to receive the JSONObject to my web service ,to test that i have created the web service and written test cases for it .Now i got hung up in passing the JSONobject from test case to web services , when i pass the json object to #post service calls it responses that Null Pointer Exception , even i have tried with passing string to it it responds null values.
I have used Annotations as follows in webservice
#consumes({Mediatype.APPLICATION_JSON})
#Consumes("application/json")
Test case As:
#Test
public void testgetmsg() {
String msg = "{\"patient\":[{\"id\":\"6\",\"title\":\"Test\"}]}";
try {
JSONObject obj = new JSONObject(new JSONTokener(msg));
WebResource resource = client.resource( "https://localhost:8443/../../resources/create");
ClientResponse response = resource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).
entity(obj).post(ClientResponse.class,JSONObject.class);
}
}
can any body guide me to proceed further ?
Thanks in Advance

You don't need to create the json object, you can just pass the string.
you should
ClientResponse response = resource.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, msg);

//CLIENT
public static void createStudent() {
String input = "{\"id\":12,\"firstName\":\"Fade To Black\",\"lastName\":\"Joy\"}";
ClientResponse response = service.path("class/post")
.type("application/json").post(ClientResponse.class, input);
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
System.out.println(response.getStatus()+ "OK");
}
Instead of using code client you can use add on firefox (POSTER) to passing value as json or formparam...
// create new student SERVER
//class
#POST
#Path("post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response createStudent(Student st) {
// add new student
StudentDAO.instance.getModelStudent().put("8", st);
// response status code
return Response.status(200).entity(st).build();
}

Related

How to send multiple HTTP requests from the same service in Java?

Java noob here. I'm trying to develop a web service as per the following diagram.
When a POST request is sent to the REST server, with certain values, the values (being read from a list, in a loop) get inserted in a table (new row with an id). Server returns HTTP 202 Accepted.
To ensure that the resource(with id from 1) is created, a GET request is issued that returns the POJO as Json.
Finally a PATCH request is sent to update a certain column.
I have written a service class that does all three tasks when each API is called individually. I need to implement something that would automatically execute steps 2 and 3 when a POST request is sent to the server. Here's my code so far.
#Path("attachments")
public class FilesService {
private TiedostoService tiedostoService;
private AttachmentService attachmentService;
#GET
#Path("{id}")
#Produces({MediaType.APPLICATION_JSON})
public Response listAttachmentsAsJson(#PathParam("id") Integer attachmentId) throws Exception {
attachmentService = new AttachmentService();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Attachment attachment = attachmentService.getAttachment(attachmentId);
String jsonString = gson.toJson(attachment.toString());
return Response.status(Response.Status.OK).entity(jsonString).build();
}
#PATCH
#Path("{id}")
#Produces({MediaType.APPLICATION_JSON})
public Response patchAttachments(#PathParam("id") Integer attachmentId) throws Exception {
attachmentService = new AttachmentService();
Integer update = attachmentService.update(attachmentId);
String jsonString = new Gson().toJson(update);
return Response.status(Response.Status.ACCEPTED).entity(jsonString).build();
}
#POST
#Produces({MediaType.APPLICATION_JSON})
public Response migrateToMinio(#Context UriInfo uriInfo) throws Exception {
Response response;
List<String> responseList = new ArrayList<>();
tiedostoService = new TiedostoService();
attachmentService = new AttachmentService();
List<Tiedosto> tiedostoList = tiedostoService.getAllFiles();
String responseString = null;
int i = 1;
for (Tiedosto tiedosto : tiedostoList) {
Attachment attachment = new Attachment();
attachment.setCustomerId(tiedosto.getCustomerId());
attachment.setSize(tiedosto.getFileSize());
Integer id = attachmentService.createNew(attachment);
if (id == 1) {
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(Integer.toString(i));
response = Response.created(builder.build()).build();
System.out.println(response);
responseString = response.toString();
}
responseList.add(responseString);
i++;
}
String jsonString = new Gson().toJson(responseList);
return Response.status(Response.Status.OK).entity(jsonString).build();
}
}
when I test the individual endpoints with curl or postman, they work as expected, but I got stuck on how to execute GET and PATCH automatically after POST. I'd really appreciate some advice/suggestions/help.

java rest web service by post method

I am trying to do a java rest web service using "POST" method.But i am unable to access the passed parameter. Here is my client part to invoke the web service.
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/wsRevDash/rest/post/testing");
Form form=new Form();
form.add("sc","pqr");
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class,form);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
And here is my java rest web service.
#POST
#Path("testing")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String createDataInJSON(#FormParam("sc") String data) {
System.out.println("Hello"+data);
JSONObject jObjDevice = new JSONObject();
jObjDevice.put("Hello",data);
return jObjDevice.toJSONString();
}
When i run on SoapUI,I am getting {"Hello":null}.
Please suggest me some way to cope with this.
Try changing form to a String:
String input = new Gson().toJson(form);
And pass in input to the response:
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class,input);
And amend your web service to something like:
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "Hello: " + data;
return Response.status(200).entity(result).build();
}
And you need to remove 'testing' from your initial path:
WebResource webResource = client.resource("http://localhost:8080/wsRevDash/rest/post/testing"); <---- here
And include a slash before it in the web service:
#Path("/testing")

How to pass multiple parameters to Jersey POST method

I am trying to pass multiple parameters to Jersey POST method . Currently I am following below steps to pass a single parameter to Jersey POST method.
Client client = ClientBuilder.newClient();
WebTarget target= client.target("http://localhost:8080/Rest/rest/subuser").path("/insertSubUser");
SubUserBean subUserBean=new SubUserBean();
subUserBean.setIdUser(1);
subUserBean.setIdSubUserType(1);
subUserBean.setIdSubUser(15);
subUserBean.setFirstName("Haritha");
subUserBean.setLastName("Wijerathna");
subUserBean.setNumberOfDaysToEditRecord(14);
subUserBean.setUserName("haritha");
subUserBean.setPassword("hariwi88");
subUserBean.setDateCreated(Common.getSQLCurrentTimeStamp());
subUserBean.setLastUpdated(Common.getSQLCurrentTimeStamp());
target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(subUserBean, MediaType.APPLICATION_JSON_TYPE));
SubUserJSONService.java
#Path("/subuser")
public class SubUserJSONService {
#POST
#Path("/insertSubUser")
#Consumes(MediaType.APPLICATION_JSON)
public String updateSubUser(SubUserBean bean){
SubUserInterface table = new SubUserTable();
String result= table.insertSubUser(bean);
return result;
}
}
Now, I want to pass parameters to following method via Jersey POST method.
public String insertHistory(List<SocialHistoryBean> list, String comment){
//my stuffs
}
Have any ideas to do above work ?
Thank you.
You can try using MultivaluedMap.Add form data and send it to the server. An example below, code is not tested just for demo/logic flow.
WebTarget webTarget = client.target("http://www.example.com/some/resource");
MultivaluedMap<List, String> formData = new MultivaluedHashMap<List, String>();
formData.add(List, "list1");
formData.add("key2", "value2");
Response response = webTarget.request().post(Entity.form(formData));
Consume this on server side something like
#Path("/uripath")
#POST -- if this is post or #GET
#Consumes("application/x-www-form-urlencoded;charset=UTF-8") or json..
#Produces("application/json")
public void methodNameHere(#FormParam("list") List<String> list1, #FormParam("key2") String val2) {
System.out.println("Here are I am");
System.out.println("list1" + list1.size);
System.out.println("val2" + val2);
}
Read more here in docs..
In case you're using Jersey 1.x, check this example on how to post multiple objects as #FormParam
Client: (pure Java):
public Response testPost(String param1, String param2) {
// Build the request string in this format:
// String request = "param1=1&param2=2";
String request = "param1=" + param1+ "&param2=" + param2;
WebClient client = WebClient.create(...);
return client.path(CONTROLLER_BASE_URI + "/test")
.post(request);
}
Server:
#Path("/test")
#POST
#Produces(MediaType.APPLICATION_JSON)
public void test(#FormParam("param1") String param1, #FormParam("param2") String param2) {
...
}
JSON data cannot be passed to the server in a List. This means that you should create a wrapper around your SocialHistoryBean class (i.e around the list that holds your objects)
#XmlRootElement(name = "uw")
public class SocialHistoryBeanWrapper implements Serializable {
private List<SocialHistoryBean> sList ;//this will hold your SocialHistoryBean instances
public SocialHistoryBeanWrapper(){
sList = new ArrayList<User>();
}
public List<User> getUsrList(){
return sList;
}
}
Your server side code will be like
#POST
#Path("/history")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String insertHistory( #QueryParam("comment") String comment, SocialHistoryBeanWrapper uw) {
do whatever you want with your history data
//userData.setUser(uw.getUsrList().get(0));
return comment; //just echo the string that we have sent from client
}
Note that comment is passed with #QueryParam (this means it's not part of the POST request (body) but is rather encoded in the URL string. For this to work, you can call your service as (the client code)
WebTarget target = client.target(UriBuilder.fromUri("http://localhost:8088/Rest/rest/subuser").build());
SocialHistoryBeanWrapper uw = new SocialHistoryBeanWrapper();
//just populate whatever fields you have;
uw.getUsrList().get(0).setName("Mark Foster");
uw.getUsrList().get(0).setProfession("writer");
uw.getUsrList().get(0).setId(55);
String s = target.path("history").queryParam("comment", "OK").request()
.accept(MediaType.TEXT_PLAIN).post(Entity.entity(uw, MediaType.APPLICATION_JSON), String.class);
System.out.println(s);//this prints OK

How to get data from response

I have created 2 web services and I was able to send some data.
Using this three lines of code
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz");
HttpResponse response = client.execute(request);
In this situation, the method that I posted send to a Web Server the 2 data.
#Path("/domethod")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
public String doLogin(#QueryParam("data1") String d1, #QueryParam("data2") String d2){
String response = "";
System.out.println("Data: d1="+d1+"; d2="+d2);
if(checkData(d1, d1)){
response = Utitlity.constructJSON("tag",true);
}else{
response = Utitlity.constructJSON("tag", false, "Error");
}
return response;
}
System.out works correctely and print: d1=abc; d2=xyz
But now the application isn't able to return response to the first method.
How I can get the response?
You're already getting the response here:
HttpResponse response = client.execute(request);
And since you're already using org.apache.httpcomponents you can do something like:
String result = EntityUtils.toString(response.getEntity());
After that you have your data as a string, simply do what you wish with it.
EDIT:
A little bit more information, your data is in the entity of the response, which is an HttpEntity object. You can get the content from there as an InputStream and read it as you wish, my example was for a simple string.
First of all, I would annotate with get the method. Then I would use a Java Class and let the library convert the class to json for me.
Try to do this:
#GET
#Path("/domethod")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
public String doLogin(#QueryParam("data1") String d1, #QueryParam("data2") String d2){
Response response = new Response();
System.out.println("Data: d1="+d1+"; d2="+d2);
if(checkData(d1, d1)){
//set in response the tag property to true and maybe another property to OK
response.setTag(true);
response.setStatus("OK");
}else{
//set in response the tag property to false and maybe another property to ERROR
response.setTag(false);
response.setStatus("ERROR");
}
return response;
}

Need Jersey client api way for posting a webrequest with json payload and headers

I am writing a client for one of my REST API using jersey(org.glassfish.jersey.client.*).
api url is : http://localhost:5676/searchws/search/getresults (POST)
this api returns a json response. i need to provide a payload using jersey client and thats where i am stuck. FOllowing is a sample extract of payload which i need to provide (preferably as string)
Question is how can i provide a payload (XML/JSON) as string or entity to my webtarget.
I saw the answer to providing payload mentioned by calden How to send Request payload to REST API in java? but i am looking for a way to do it in jersey client.
Here is my code till now which does not work fully for post requests.
public class RequestGenerator
{
private WebTarget target;
private ClientConfig config;
private Client client;
private Response response;
public RequestGenerator(Method RequestSendingMethod) throws Exception
{
switch (RequestSendingMethod)
{
case POST :
config = new ClientConfig();
client = ClientBuilder.newClient(config);
target = client.target("http://localhost:5676/searchws").path("search").path("getresults");
String payload = "{\"query\":\"(filter:(\\\"google\\\")) AND (count_options_availbale:[1 TO *])\"}"; //This is just a sample json payload actual one is pretty large
response = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json("")); // What to do here
String jsonLine = response.readEntity(String.class);
System.out.println(jsonLine);
}
}
You specify payload as the argument to Entity.json
String payload = "{\"query\":\"(filter:(\\\"google\\\")) AND (count_options_availbale:[1 TO *])\"}";
response = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(payload));
I got this working using following code, Salil's code works fine as well(+1 with thanks to him), thanks everyone who contributed to this problem, loving stackoverflow:
public class RequestGenerator
{
private WebTarget target;
private ClientConfig config;
private Client client;
private Response response;
public RequestGenerator(Method RequestSendingMethod) throws Exception
{
switch (RequestSendingMethod)
{
case POST :
String payload = "\r\n{\r\n\"query\": \"google \",\r\n\"rows\": 50,\r\n\"return_docs\": true,\r\n\"is_facet\": true\r\n}"; //this is escapped json string in single line
config = new ClientConfig();
client = ClientBuilder.newClient(config);
target = client.target("http://localhost:7400/searchws/search/getresults");
response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(payload, MediaType.APPLICATION_JSON), Response.class);
processresponse(response); //This could be any method which processes your json response and gets you your desired data.
System.out.println(response.readEntity(String.class));
break;
case GET :
config = new ClientConfig();
client = ClientBuilder.newClient(config);
target = client.target("http://localhost:7400/search-service/searchservice").path("search").path("results").path("tiger");
response = target.request().accept(MediaType.APPLICATION_JSON).get();
processresponse(response); //This could be any method which processes your json response and gets you your desired data.
System.out.println(response.readEntity(String.class));
}
}

Categories