I just made a new Springboot Project and every time I want so implement the Controller for the Mapping from my API into my Database I get the statuscode 302.
The class I want to put into the db is a Movie, here is the Moviecontroller
#RestController()
#RequestMapping(path = "movie")
public class MovieController {
private final MovieService movieService;
#Autowired
public MovieController(MovieService movieService){ this.movieService = movieService; }
#GetMapping("getmovie")
public List<Movie> getMovie(){
return movieService.getMovie();
}
#PostMapping(path = "postmovie")
public void addNewMovie(#RequestBody Movie movie){
movieService.addNewMovie(movie);
}
}
The Class which handles the API has this method in it which is supposed to handle a Movie Json and send it via http to the Controller. Since I want to post the minimum code necessary for this Problem I do not post the complete class. The Route is...
#Route(value = "addmovie", layout = MainLayout.class)
public void saveMovieInDatabase(int movieId, String title, String posterSrc, int releaseDate,int length) throws IOException {
String movieString = new ObjectMapper().writeValueAsString(new Movie(movieId,title,posterSrc,releaseDate,length));
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/movie/postmovie");
post.setEntity(new StringEntity(movieString));
post.setHeader("Accept","application/json");
post.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
}
Related
My issue is when I try this I get a media type error, then I changed the header. Now I receive a 500 error. The problem isnt the api , on postman it works perfectly , am I doing something wrong in my code when requesting a post?
My object model
public class EmailModel {
private String module;
private String notificationGroupType;
private String notificationGroupCode;
private String notificationType;
private String inLineRecipients;
private String eventCode;
private HashMap<String, Object> metaData;
public EmailModel() {
this.module = "CORE";
this.notificationGroupType = "PORTAL";
this.notificationGroupCode = "DEFAULT";
this.notificationType = "EMAIL";
this.inLineRecipients = "[chrispotjnr#gmail.com,chris#mqattach.com]";
this.eventCode = "DEFAULT";
this.metaData = metaData;
}
}
My Controller
It should send a post request with a object body, the emails get sent
#RequestMapping(value = "test", method = RequestMethod.Post)
public void post() throws Exception {
String uri = "TestUrl";
EmailModel em = new EmailModel();
EmailModel data = em;
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.headers("Content-Type", "application/json")
.uri(URI.create(uri))
.POST(HttpRequest.BodyPublishers.ofString(String.valueOf(data)))
.build();
HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding());
System.out.println(em);
System.out.println(response.statusCode());
}
postmanImage
You must to convert EmailModel to json format by ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
String data = objectMapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(em);
and change POST to :
.POST(HttpRequest.BodyPublishers.ofString(data))
See more about ObjectMapper
Capture requests and cookies(on the left side of setting icon)
->Request
->port and put the port number there
I am using java.net.http.HttpClient in my Java Spring Boot app and I noticed this weird behaviour.
When my code call HTTP request to 3rd party API, next request to different 3rd party API returns always as bad request (400). When I execute this request first, it works just fine.
When I restart the app, first API call is always successful, but second one is always bad and so I have to call it again after some timeout and then it work.
So I was thinking, if there is any form of "cache" that remember previous settings or whatever from previous request, because second request to different API is always bad. When I inspected HttpRequest in debugger, it seems okay to me and there was nothing really different from the one that worked.
Here is my bean config
#Configuration
public class HttpClientBean {
#Bean
public HttpClient httpClient() {
return HttpClient.newHttpClient();
}
}
HttpRequest builder
public static HttpRequest buildGetRequest(final String url) {
return HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
}
public static HttpRequest buildPostRequest(final String url, final String body) {
return HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.uri(URI.create(url))
.setHeader(CONTENT_TYPE, APPLICATION_JSON)
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
}
and here is HttpService
#Service
public class HttpServiceImpl implements HttpService {
private final HttpClient httpClient;
#Autowired
public HttpServiceImpl(final HttpClient httpClient) {
this.httpClient = httpClient;
}
#Override
public HttpResponse<String> sendGetRequestWithParams(final String url, final String params) throws Exception {
final HttpRequest request = buildGetRequest(url, params);
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
#Override
public HttpResponse<String> sendGetRequestWithoutParams(final String url) throws Exception {
final HttpRequest request = buildGetRequest(url);
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
#Override
public HttpResponse<String> sendPostRequestWithBody(final String url, final String body) throws Exception {
final HttpRequest request = buildPostRequest(url, body);
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
}
Thank you for your advices.
I have developed a simple REST API which serves a simple HTTP PUT request using Spring Boot 2.3.1.RELEASE & Oracle JDK 14. Below is the server side REST endpoint:
#Controller
#RequestMapping("/api/documents")
public class DocumentController {
#PutMapping(value = "/setCurrentTenant", consumes = "multipart/form-data")
public ResponseEntity<?> setCurrentTenant(
#RequestParam(value = "documentId", required = false) Long documentId,
#RequestParam("tenantId") Long tenantId) {
return documentService.setCurrentTenant(documentId, tenantId);
}
}
And the client side code:
HttpPut putRequest = new HttpPut("http://localhost:8080/api/document/setCurrentTenant");
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
builder.addTextBody("documentId", "1");
builder.addTextBody("tenantId", "10");
HttpEntity setCurrentTenantEntity = entityBuilder.build();
putRequest.setEntity(setCurrentTenantEntity);
httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(putRequest);
I tried to run the code and everything is okay but when the client request is sent to the server, Spring would log an exception like this:
Resolved [org.springframework.web.bind.MissingServletRequestParameterException:
Required Long parameter 'tenantId' is not present]
Am I missing something?
You should send tenantId as request parameter like
http://localhost:8080/api/document/setCurrentTenant?tenantId=10
I'm concern that why are you consume a multipart/form-data while you're not sending any file/binary data
class TenantRequest {
Long tenantId;
Long documentId;
//seter, getter
}
#PutMapping(value = "/setCurrentTenant", consumes = "multipart/form-data")
public ResponseEntity<?> setCurrentTenant(TenantRequest request) {
// TODO
}
or
#PutMapping(value = "/setCurrentTenant", consumes = "multipart/form-data")
public ResponseEntity<?> setCurrentTenant(#ModelAttribute TenantRequest request) {
// TODO
}
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.
I have an EJB application which needs to send a XML object to a RESTfull service through HTTP Post. (All in the same infrastructure park)
I have seen some examples which the XML object is converted to String before send it to the service. However, I want to pass all the XML object itself. (I suppose it's possible)
For instance, in a web application architecture, I would do that by using RestTemplate, as follow:
RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class);
Now, I strictly should do the same using HttpURLConnection instead.
Someone can help me by showing some example?
The rest service only consumes "application/XML" and returns a String.
Follow my RESTfull signature and my XML object.
RESTFull Service
#RestController
#RequestMapping(value = "/analytic/")
public class AnalyticController {
#RequestMapping(value = "/requestProcessor", method = RequestMethod.POST, consumes = MediaType.APPLICATION_XML_VALUE)
public String analyticRequest(#RequestBody ServiceRequest serviceRequest){
//Some code here...
return "0";
}
}
Domain
#XmlRootElement(name = "ServiceRequest")
public class ServiceRequest implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#XmlAttribute(name = "Method")
private String method;
#XmlElement(name = "Credential")
private Credential credential;
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Credential getCredential() {
return credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
}
Thanks in advance.
Thank you all for your thoughts!
I could solve my issue by doing the below code.
URL url = new URL("http://server:port/service_path");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
JAXBContext jaxbContext = JAXBContext.newInstance(MyClass.class);
jaxbContext.createMarshaller().marshal(MyClass, os);
os.flush();