While working on REST API, I am using POST method to fetch data from Mongo DB using #FormParam annotation. When I use GET type, then it returns the response in JSON and while changing the method from GET to POST, I am getting blank response.
The code:
//GetResponse.java
//
#Path("/Location")
public class GetProjectLocationResponse {
#POST
#Path("/State")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Object[] addBuild2(
#FormParam("Country") String Country,
#FormParam("State") String State) throws UnknownHostException, JSONException
{
System.out.println("ïnside Location");
Location loc = new Location();
List<DBObject> basicDBList=(List<DBObject>) loc.getState2(Country, State); //calling state method
return basicDBList.toArray();
}
//Location.java
//This defines the list of available zipcpdes on the basis on parameter 'Country' and 'States'.
public List<DBObject> getState2(String Country, String State) throws UnknownHostException {
DB db=ConnectToDB.getConnection();
DBCollection collection = db.getCollection("location");
BasicDBObject obj = new BasicDBObject();
obj.put("Country",Country);
obj.put("State",State);
BasicDBObject fields = new BasicDBObject();
fields.put("_id", 0);
DBCursor cursor = collection.find(obj, fields);
List<DBObject> obj1 =cursor.toArray();
System.out.println(""+obj1);
return obj1;
}
}
//index.html
//This file includes parameters 'country' and 'states' to return the JSON response.
<form action="rest/Location/State" method="post">
Enter Country:<input type="text" name="Country"/><br/><br/>
Enter State:<input type="text" name="State"/><br/><br/>
<input type="submit" value="submit"/>
I have checked the code but did not find any clue what is wrong in this that causing this blank response for POST type, while its working fine for GET type. I though it should have worked for POST type as the code specification is correct for both type. Please specify any issue there. Thanks in advance
You are using POST for a different and wrong purpose here.
Use GET for retrieving data and POST for creation of the required entity. A typical response from a POST call would be 201 - Created and the UI should not expect any response from the POST call.
HTTP POST was not specified to return data and do not expect it to return.
Similar question :
Can I use POST method to get data and GET method to post data?
Related
I am facing an issue while making a request body to do an API call in Java.
Required Body
{
"id" : [1,2]
}
I have an integer array with me lets say arr, I am creating the request something like:-
JSONObject jsonObject = new JSONObject();
jsonObject.put("id",Arrays.toString(arr));
String stringBody = jsonObject.toJSONString();
RequestSpecification specification = RestAssured.with();
specification.body(stringBody);
Response response = specification.post(endpoint);
What it actually does is make the request body as something like below.
{
"id" : "[1,2]"
}
As it sends the value as String so my server throws an error, Expected a list of items but got type \"unicode\".
Can somebody help me in here. How do I send it in raw format instead of String.
Use
jsonObject.put("id",Arrays.asList(arr));
to build the json body.
I Have a RESTful web service created using Java connected to a db containing cars and implamenting CRUD operations and testing using Postman.
Currently it just uses the conventional HTTP GET returning status 200ok when a car in the database is returned successfully.
I am trying now to implement a conditional GET to return status 304 when a second GET request is submitted and the entity has not been modified from the previous GET request.
Reading about the conditional GET i know it uses the Last-modified and if-modified-since headers but struggling on how to go about implementing this.
Within the db i have a trigger to update a TIMESTAMP associated with each entity after they have been modified and i presume this will be the value that will be checked to see if the entity has been modified since the last request ?
Any Help appreciated
The Current GET request:
#GET
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("{reg}")
public Response getOneCar(#PathParam("reg") String reg) {
Car car = dao.getCarDetails(reg);
System.out.println("GET CarReg == "+reg);
if(car == null){ // no car with that reg exists
return Response
.status(Response.Status.NOT_FOUND)
.entity("<carNotFound reg='"+reg+"' />")
.build();
}else{
car.setLink(new ArrayList<Link>());
Link linkSelf = new Link();
linkSelf.setRel("self");
linkSelf.setUri(context.getPath());
Link deleteLink = new Link();
deleteLink.setRel("/linkrels/car/delete");
deleteLink.setUri(context.getPath());
Link updateLink = new Link();
updateLink.setRel("/linkrels/car/update");
updateLink.setUri(context.getPath());
car.getLink().add(linkSelf);
car.getLink().add(deleteLink);
car.getLink().add(updateLink);
return Response
.status(Response.Status.OK)
.entity(car)
.build();
}
}
Example of one of the entities:
<car>
<id>3</id>
<regNo>03G333</regNo>
<make>Ford</make>
<model>Focus</model>
<link rel="self" uri="cars/03G333"/>
<link rel="/linkrels/car/delete" uri="cars/03G333"/>
<link rel="/linkrels/car/update" uri="cars/03G333"/>
<time>2018-03-23 10:00:05.772</time>
</car>
Thanks for the response #Andrew,
I am currently trying to do this using the "If-Modified-Since" and "Last-Modified" Headers.
On The server i am sending a "Last-Modified" Header to the client which takes the timestamp from the current car in the db as shown in the image --> postman server responce
Now i am trying to configure postman to send back the "if-Modified-Since" header.
if i compare these values and depending on the timestamp being the same or different i can determine the response to be sent back.
currently having trouble configuring postman to send the "If-Modified-Since" Header and then taking this value in on the Server somehow.
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String lastmodifiedDate = car.getTime();
date = sdf.parse(lastmodifiedDate);
} catch (ParseException ex) {
}
return Response
.status(Response.Status.OK).lastModified(date)
.entity(car)
.build();
}
}
So I have in my code POST method :
#POST
#Path("/send/{userPost}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public Response sendUser(#PathParam("userPost") String userPost ) {
List<Post>userPosts = new ArrayList();
Post post = new Post(99,userPost,"Bartek Szlapa");
userPosts.add(post);
User user = new User(99,"Bartek","Szlapa",userPosts);
String output = user.toString();
return Response.status(200).entity(output).build();
}
unfortunately its not working. I'm getting 404 error. Server is configured correctly because other methods work perfectly. Funny thing is that when I remove {userPost} , parameter : #PathParam("userPost") String userPost and send empty request : http://localhost:8080/JavaAPI/rest/api/send it works - I'm getting new User object with null at some fields. Do you know why I cannot send parameter ? Thanks in advance for help! :)
What you are sending is not a path parameter to send your value as a path parameter based on your api , let us say you are trying to send "test"
http://localhost:8080/JavaAPI/rest/api/send/test
if you want to use query params
#POST
#Path("/send")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public Response sendUser(#QueryParam("userPost") String userPost ) {
and your request should be
http://localhost:8080/JavaAPI/rest/api/send?userPost=test
Your "userPost" parameter is not in the Path : localhost:8080/JavaAPI/rest/api/send?=test
You defined this path :
#Path("/send/{userPost}")
So, your URI should be :
localhost:8080/JavaAPI/rest/api/send/test
I'm building an application that has these methods in the Controller for a form handling:
//This will prepare the model and populate the form
#RequestMapping(value="verbete",method = RequestMethod.GET, params="new")
public String addVerbete(#ModelAttribute("verbeteform") VerbeteForm verbeteForm,
Map<String, Object> model){
verbeteForm.getNomes().add(new NomesVerbete());
// add one significado
verbeteForm.getSignificados().add(new SignificadosVerbete());
// depois de implementar o Security
verbeteForm.getVerbete().setAutor(usuarioService.buscarUsuarioPorLogin("greati"));
// seta a data
verbeteForm.getVerbete().setDataLancamento(new Date());
// popula categorias
verbeteForm.setCategorias(verbeteService.listarCategorias());
return "editorVerbete";
}
#RequestMapping(value="verbete", params="new", method = RequestMethod.POST)
public String addVerbeteFromForm(#ModelAttribute("verbeteform") VerbeteForm verbeteForm,
Map<String, Object> model){
Verbete verbete = verbeteForm.getVerbete();
List<NomesVerbete> nomes = verbeteForm.getNomes();
List<SignificadosVerbete> significados = verbeteForm.getSignificados();
long idVerbeteSalvo = verbeteService.addVerbete(verbete);
Verbete verbeteSalvo = verbeteService.getVerbetePorId(idVerbeteSalvo);
for(NomesVerbete nome:nomes){
nome.setVerbete(verbeteSalvo);
verbeteService.addNomesVerbete(nome);
}
for(SignificadosVerbete significado:significados){
significado.setVerbete(verbeteSalvo);
significado.setCategoria(verbeteService.getCategoriaPorNome(significado.getCategoria().getNome()));
verbeteService.addSignificadosVerbete(significado);
}
return "editorVerbete";
}
So, I was expecting that the date and the author would be setted in the model, but, when I submit the form, it says that the attributes dataLancamento (it's a date) and autor are not in the model, throwing an error because they cannot be null in the database.
Maybe I didn't understand how #ModelAttribute works, or maybe I'm doing something wrong.
A solution would be set the dataLancamento and autor in the second method, but I don't know if it's right. So, could you show me a way?
(Some words are in Portuguese... Please, tell me if it's a problem.)
When the first method is execute and the form is rendered the first time, the autor should be in the model. So using ${verbeteform.autor} should print the autor field.
But when you submit the form, the model is fullfilled with the data in the form. So if the form doesnt have a autor field like:
<form:form modelAttribute="verbeteform" method="POST">
<form:input path="autor"/>
</form:form>
the value is not added to the model, so in the second controller you have a null value in the autor field because the model is regenerated.
I'm creating a REST Client in Java with RestTemplate from Spring Framework.
Everything is fine until i have to do a post with postForLocation.
The webservice i'm having access return a json with informations about the POST ACTION.
In PHP it's fine but i really don't understand how to do in Java with RestTemplate.
public String doLogin()
{
Map<String, String> args = new HashMap<String, String>();
args.put("email", AUTH_USER);
args.put("token", AUTH_PASS);
String result = restTemplate.postForLocation(API_URL + "account/authenticate/?email={email}&token={token}", String.class, args);
return result;
}
This returns NULL.
With same code but using getForObject (and of course, changing the URL to something right) I have a full response, i.e. this works:
String result = restTemplate.getForObject(url, String.class);
So... how get the RESPONSE from a postForLocation?
Obs.: Sorry if this question is dumb. I'm beginner in Java
The postForLocation method returns the value for the Location header. You should use postForObject with the String class, which returns the server's response.
So like this:
String result = restTemplate.postForObject(API_URL + "account/authenticate/?email={email}&token={token}", String.class, args);
This will return the response as a string.
Thanks to one of answers i've figured out how get the response from a POST with Spring by using the postForObject
String result = restTemplate.postForObject(API_URL + "account/authenticate/?email="+ AUTH_USER +"&token="+ AUTH_PASS, null, String.class);
For some reason i can't use arguments with MAP and have to put them inline in URL. But that's fine for me.