Retrieve data from a HTTP get request - java

How do I access the parameters sent in a jQuery $.get request?
$(document).ready(function () {
var input1 = "name has been sent";
$("#btn1").click(function(){
$.get("http://localhost:8080/RestHelloWorld/rest/message/hello", {
name: input1
});
});
Java:
#GET
#Path("/hello")
public String printMessage(#FormParam("name") String n){
System.out.println(n);
return "helloWorld";
}
The connection is fine as I am printing null to the console. How do I access the data sent within the HTTP request? I'm thinking the #FormParam is not the correct way to reference the data.

Found the correct command - (#QueryParam instead of (#FormParam
#GET
#Path("/hello")
public String printMessage(#QueryParam("name") String n){
System.out.println(n);
return "helloWorld number 2";
}

You can use #RequestParam for parameters;
#GET
#Path("/hello")
public String printMessage(#RequestParam("name") String n){
System.out.println(n);
return "helloWorld";
}
Or HttpServletRequest;
#GET
#Path("/hello")
public String printMessage(HttpServletRequest request){
System.out.println(request.getParameter("name"));
return "helloWorld";
}

Related

Send clikable url from java

I want to send clickable URL from java code to UI where it return type initially was String
#POST
#Path("/crd")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String isValid(SomeDTO SomeDTO)
throws Exception {
// business logic
catch(Exceptioin e){
return "notvalid"
}
}
Now i want send to ui url along with text(like notvalid.Click below link to
user guide)
#POST
#Path("/crd")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String isValid(SomeDTO SomeDTO)
throws Exception {
// business logic
catch(Exceptioin e){
return "notvalid"+url
}
}
before i was notvalid
---expected is notvalid.Cilck below link to user guide.
return "notvalid"+"Click here for more info";

Getting String body from Spring serverrequest

I am trying to get simple string from request body but keep getting errors
Handler:
#RestController
public class GreetingHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
String contentType = request.headers().contentType().get().toString();
String body = request.bodyToMono(String.class).toString();
return ServerResponse.ok().body(Mono.just("test"), String.class);
}
}
Router:
#Configuration
public class GreetingRouter {
#Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {
return RouterFunctions
.route(RequestPredicates.POST("/hello"),greetingHandler::hello);
}
}
Request works i can see the contenType (plainTexT) and i get the response in postman but no way i cant get to request body. The most common error i get is MonoOnErrorResume. How do i convert the body from request into String?
You will have to block to get to the actual body string:
String body = request.bodyToMono(String.class).block();
toString() will just give you the string representation of your Mono object.
Here is what block does:
https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#block--
Update:
I wasn't aware that blocking on the http thread is not possible (anymore?).
Here is an adapted version of your hello controller method that prints "Hello yourInput" on the console and also returns that string in the response.
public Mono<ServerResponse> hello(ServerRequest request) {
Mono<String> requestMono = request.bodyToMono(String.class);
Mono<String> mapped = requestMono.map(name -> "Hello " + name)
.doOnSuccess(s -> System.out.println(s));
return ServerResponse.ok().body(mapped, String.class);
}
Can you use #RequestBody annotation?
public Mono<ServerResponse> hello(#RequestBody String body, ServerRequest request) {
String contentType = request.headers().contentType().get().toString();
return ServerResponse.ok().body(Mono.just("test"), String.class);
}

Spring boot Java post request

I am trying to do a simple post request from React (client side) to Java server side. Here is my controller below.
package com.va.med.dashboard.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.va.med.dashboard.services.VistaServiceImpl;
import gov.va.med.exception.FoundationsException;
#RestController
#RequestMapping("/dashboard")
public class DashboardController {
#Autowired
private VistaServiceImpl vistaService;
#RequestMapping("/main")
String home() {
return "main route";
}
#RequestMapping("/rpc")
String test() throws FoundationsException {
vistaService.myAuth();
return "this is rpc route";
}
#RequestMapping(method = RequestMethod.POST, produces =
"application/json", value = "/vista")
#ResponseStatus(value = HttpStatus.ACCEPTED)
public String getVistaConnection(#RequestBody String ipString, #RequestBody String portString, #RequestBody String accessPin,
#RequestBody String verifyPin) {
System.out.println(ipString);
System.out.println(portString);
System.out.println(accessPin);
System.out.println(verifyPin);
vistaService.connect(ipString, portString, accessPin, verifyPin); // TO-DO populate with serialized vars
if (vistaService.connected) {
return "Connected";
} else {
return "Not Connected";
}
}
}
Below is my react axios post request
axios.post('/dashboard/vista', {
ipString: this.state.ipString,
portString: this.state.portString,
accessPin: this.state.accessPin,
verifyPin: this.state.verifyPin
})
.then(function (response){
console.log(response);
})
.catch(function (error){
console.log(error);
});
This is also the error that I am getting.
Failed to read HTTP message:
org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing:
Can anyone please shed some light on this error message? I'm coming from a pure JavaScript background so a lot of things I just don't know for Java because it is automatically implemented inside of JavaScrips language.
Thanks again in advance!
You're doing it wrong.
Instead of
public String getVistaConnection(#RequestBody String ipString, #RequestBody String portString, #RequestBody String accessPin,RequestBody String verifyPin)
You should wrap those parameters in a class:
public class YourRequestClass {
private String ipString;
private String portString;
....
// Getter/setters here
}
and your controller method will look like:
public String getVistaConnection(#RequestBody YourRequestClass request)
From #Rajmani Arya:
Since RestContoller and #RequestBody suppose to read JSON body, so in your axios.post call you should put headers Content-Type: application/json
Try to replace all #RequestBody annotations with #RequestParam
public String getVistaConnection(#RequestParam String ipString, #RequestParam String portString, #RequestParam String accessPin, #RequestParam String verifyPin)

How to read a cookie in JAX-RS (Jersey)

I followed this guide to read and create cookies but I can only read cookie that I create from the same subdomain.
For example if I create a cookie in http://localhost:8080/x/y/test/create I can read it from: http://localhost:8080/x/y/test/read but I cannot read it from http://localhost:8080/x/y/test2/read (Note the difference between test and test2)
Where is the problem? How could I read the cookie everywhere in my domain?
Here is the code:
CLASS 1
#Path("test")
public class Test {
#GET
#Path("/create")
#Produces(MediaType.TEXT_PLAIN)
public Response login() {
NewCookie cookie = new NewCookie("name", "123");
return Response.ok("OK").cookie(cookie).build();
}
#GET
#Path("/read")
#Produces(MediaType.TEXT_PLAIN)
public Response foo(#CookieParam("name") String value) {
System.out.println(value);
if (value == null) {
return Response.serverError().entity("ERROR").build();
} else {
return Response.ok(value).build();
}
}
}
CLASS 2
#Path("test2")
public class Test2 {
#GET
#Path("/read")
#Produces(MediaType.TEXT_PLAIN)
public Response foo(#CookieParam("name") String value) {
System.out.println(value);
if (value == null) {
return Response.serverError().entity("ERROR").build();
} else {
return Response.ok(value).build();
}
}
}
EDIT
The problem was at creation time. Now I create the cookie in this way:
NewCookie cookie = new NewCookie("name", "123", "/", "", "comment", 100, false);
It's a default behavior.
To set cookie to your domain, use another constructor for cookie, and set empty domain and root path:
domain = ""
path = "/"

How to pass JSON String to Jersey Rest Web-Service with Post Request

I want to create a REST Jersey Web-Service accepting JSON string as input parameter.
Also I will use post requestand from webmethod I will return one JSON string.
How can I consume this in a HTML page using Ajax post request.
I want to know what all changes I need to make it on web method to accept JSON String.
public class Hello {
#POST
public String sayPlainTextHello() {
return "Hello Jersey";
}
}
Need to break down your requests. First, you want to accept a JSON string. So on your method you need
#Consumes(MediaType.APPLICATION_JSON)
Next, you need to decide what you want your method to obtain. You can obtain a JSON string, as you suggest, in which case your method would look like this:
#Consumes(MediaType.APPLICATION_JSON)
public String sayPlainTextHello(final String input) {
Or alternatively if your JSON string maps to a Java object you could take the object directly:
#Consumes(MediaType.APPLICATION_JSON)
public String sayPlainTextHello(final MyObject input) {
You state that you want to return a JSON string. So you need:
#Produces(MediaType.APPLICATION_JSON)
And then you need to actually return a JSON string:
return "{\"result\": \"Hello world\"}";
So your full method looks something like this:
#PATH("/hello")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String sayPlainTextHello(final String input) {
return "{\"result\": \"Hello world\"}";
}
Regarding using AJAX to send and receive, it would look something like this:
var myData="{\"name\": \"John\"}";
var request = $.ajax({
url: "/hello",
type: "post",
data: myData
});
request.done(function (response, textStatus, jqXHR){
console.log("Response from server: " + response);
});
This will work. "path" is the relative URL path to be used in AJAX call.
public class Hello {
#POST
#Path("/path")
#Produces({ "text/html" })
public String sayPlainTextHello() {
return "Hello Jersey";
}
}

Categories

Resources