I am trying to make a postRequest and trying to get the object from request but the code is not getting executed. It is not getting inside the method.
I have already tried adding #componentScan in config files and #EntityScan
#RestController
#RequestMapping("/api/verify")
#CrossOrigin(origins = "*")
public class Verify {
#PostMapping(path = "/members", consumes = "application/json")
public String verify(#RequestBody DeviceDetails device) {
try {
System.out.println(device.getIpAddress());
//return "1";
return "hi";
}
catch (Exception e) {
System.out.println(e);
return "hi from err";
}
}
I expect that it should print hi to console and it should print IP Address
You're using wrong method - get (in the screenshot from postman), whereas in your mapping you're defining a post endpoint: #PostMapping(path = "/members", consumes = "application/json"). You need to change it to GetMapping or simply use post in postman. Also - check the urls and bodies if they match.
The above code has a path of /api/verify/members but in postman, it is /api/verify/call. In Postman, please correct it to /api/verify/members, change GET method to the POST method, and also please check if the JSON body is proper. Once these are fixed it should work.
Related
I am trying to access the POST API from my spring app to angular but little bit confused how to use and access the given API in my angular app.
Spring REST API
#RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
The given API is fetching the welcome message details from my oracle DB and returning a string value. I am trying to access the given REST API in my angular code through services. I had define the post service as follows
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
const headers = {'content-type':'application/text'}
return this.http.put("http://localhost:8080/API/getWelcomeMessage",null,
{'headers':headers});
}
}
As the post method requires three arguments URL, Body and header. But in my case my spring REST API doesn't contain any body and returning a string. So, I had define the body as null and change the header type to text as it is JASON by default.
At last, I am trying to access the given service method by injecting it in my component as follows-
export class LoginComponent implements OnInit {
message:string;
constructor(private loginService : LoginService) { }
ngOnInit(): void {
this.loginService.welcomeMessageService().subscribe(
response =>{
console.log(response);
this.message = response;
}
)
}
}
But when I am trying to assign the response to the string I am getting the error that string cannot be assigned to the object. I am little bit confused why this error is occurring as I had also changed the header type to string while defining my service but still getting the error.
It can be a great help if anybody guide me regarding this as I am new to angular and little bit confused with integration part of API with angular.
Use { responseType: 'text' } and also send an empty body not null
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
return this.http.put("http://localhost:8080/API/getWelcomeMessage",{},
{ responseType: 'text' });
}
}
Maybe you have copied the function wrong but check also here
#RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
This is a Post method not a put that you are trying to call
As for cors error add the following to the backend just above #Controller or #RestControler whatever you have
#CrossOrigin(value = {"http://localhost:4200"}, methods = {GET,POST,PUT,DELETE})
I an creating an endpoint with spring boot...i can upload image to folder and save it via postman everythink works good.
i have a problem with get method when i am adding the value #RequestMapping value = "getImage/{imageName:.+}" in postman i add http://localhost:8080/api/images/getImage/{burger+png}
is that corect ???
#RequestMapping(value = "api/images")
public class ImageController {
#Autowired
public ImageService imageService;
#PostMapping(value ="upload")
public ResponseEntity uploadImage(#RequestParam MultipartFile file){
return this.imageService.uploadToLocalFileSystem(file);
}
#GetMapping(
value = "getImage/{imageName:.+}",
produces = {MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_GIF_VALUE,MediaType.IMAGE_PNG_VALUE}
)
public #ResponseBody byte[] getImageWithMediaType(#PathVariable(name = "imageName") String fileName) throws IOException {
return this.imageService.getImageWithMediaType(fileName);
}
}
what should be the correct request url ???
It seems like it's reaching the backend fine, but failing to find path. Usually API endpoints end with parameters with a slug or query param. You can try either of the following to see if it works:
http://localhost:8080/api/images/getImage/burger.png
http://localhost:8080/api/images/getImage?imageName=burger.png
Keep in mind, you want to make sure that file exists at the path it's mentioning at the very top of the trace in the JSON response. This may depend on how you uploaded the file and with what name.
I am developing chat application using java springboot and Angular 7. I am using events in spring boot and angular. I am trying to generate events in spring boot for angular to listen the event. However, I am getting following error:
Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
Here is my controller code in springboot:
#CrossOrigin("*")
#RestController
#RequestMapping("/chat")
public class MessageController {
#Autowired
MessageService messageService;
#Autowired
private ApplicationEventPublisher applicationEventPublisher;
private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
#PostMapping(consumes = "application/json", produces = "application/json")
public GenericApiResponse<Map<String, Object>>message(#RequestBody MessageRequest req) {
logger.info("MessageController:: messagemethod [POST] /chat");
GenericApiResponse<Map<String, Object>> responseObj = new GenericApiResponse<>();
Object returnValue = new Object();
try {
returnValue = messageService.translateText(req);
} catch (Exception e) {
e.printStackTrace();
logger.error("EXCEPTION: "+e.getStackTrace().toString());
responseObj.setStatus(Constants.ERROR);
responseObj.setMessage("Internal Server Error");
}
Map<String, Object> resMap = new HashMap<>();
resMap.put("result", returnValue);
resMap.put("sender", req.getSender());
responseObj.setResponseObject(resMap);
responseObj.setStatus(Constants.SUCCESS);
MessageEvent messageEvent = new MessageEvent(this,"eventName", responseObj);
applicationEventPublisher.publishEvent(messageEvent);
return responseObj;
}
I am unable to figure out what is the issue and how to solve it. Please help me to solve this issue.
Thanks in advance :)
From first look at your code, I can observe following problems:
#ResponseBody is added but no response is returned i.e. method type is void.
produces = "application/json" doesn't make sense for a void method returning no response.
Hence, for a rest endpoint always return some response. You can fix it by putting following as return statement in the end in your method:
return ResponseEntity.ok("your message");
Also, #ResponseBody means that response is always serialized to json hence, no need to specify , produces = "application/json" explicitly.
Update:
Can you please also try replacing consumes = "application/json", produces = "application/json" with
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
And
ensure that request headers are set to application/json.
Also, ensrue jackson dependencies are in place.
Solution: EventSource in angular takes Content-Type : text/event-stream by default. So I created new method and added #RequestHeader(value = "Content-Type", defaultValue = "text/event-stream") as parameter.
Automatic conversion of Objects are neglected if you don't have getter method for the return type object. If you don't have getter method for GenericApiResponse object add one.
I use Intellij idea and I created a spring-boot project. My problem is with request methods, when I use GET method, it works but POST,PUT and DELETE methods throw that damn Whitelabel Error Page!!
The error content is :
"There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported"
#RestController
#RequestMapping("/")
public class CustomerInquiryController {
#GetMapping("/get")
public String getMessage(){
return "msg is fetched!";
}
#PostMapping("/post")
public String addMessage(){
return "msg is added!";
}
#PutMapping("/put")
public String editMessage(){
return "msg is edited!";
}
#DeleteMapping("/del")
public String deleteMessage(){
return "msg is deleted!";
}
}
Your browser only makes GET requests (and POST if through a form), you can't test other request methods from your browser. Use postman, curl, wget or a similar tool to access those endpoints.
Try curl -X POST http://<YOUR_HOST>:<PORT>/post in your command line. If this returns msg is added! your POST is working. Try using alternate tool or form post to then post data.
Replace with hostname or ip you are using and with port number before running the command.
It worked with adding "method = {RequestMethod.GET, RequestMethod.POST}" to class annotation according to cardouken's comment. Earlier, I used this annotation before my method but it didn't work. It is very strange.
Well, actually, you don't even need a #RequestMapping("/").
This would have done the job:
#RestController
public class CustomerInquiryController {
#GetMapping("/get")
public String getMessage(){
return "msg is fetched!";
}
#PostMapping("/post")
public String addMessage(){
return "msg is added!";
}
// .. other mappings..
}
HTML forms support GET and POST.
HTML5 at one point added PUT/DELETE, but those were dropped.
I'm a little bit confused. I'm writing an MVC application and have a simple controller like this:
#Controller
public class ProfileController {
final String DEFAULT_MALE_AVATAR = "../resources/graphics/avatarMan.PNG";
final String DEAULT_FEMALE_AVATAR = "../resources/graphics/avatarWoman.PNG";
#Autowired
UserService userService;
#RequestMapping(value = "/profile", method = RequestMethod.GET)
public String index() {
return "user/profile";
}
#RequestMapping(value = "profile/getavatar", method = RequestMethod.GET)
public #ResponseBody String getLoggedUserAvatar() {
String userMail = SecurityContextHolder.getContext()
.getAuthentication().getName();
User loggedUser;
if (userMail != null) {
loggedUser = userService.findUserByEmail(userMail);
return loggedUser.getAvatar();
} else {
return DEFAULT_MALE_AVATAR;
}
}
I've also got a simple js file called with "onload" in my body html tag while entering /profile section.
function init() {
var url = "profile/getavatar";
$.ajax({
url : url
}).then(function(data) {
avatarLink = data;
loadAvatar(avatarLink);
});
function loadAvatar(avatarLink){
$("#userAvatar").attr("src", avatarLink);
}
}
And for some strange reason I get ridirected to "profile/getavatar" and the page contains text with value returned by getLoggedUserAvatar(). The funny thing is I've also got some other controllers to other sections with almost the same js files and controllers - and they work like a charm.
What am I missing?
I hope when you hit the URL directly, you are getting expected response. If that is not happening, then there is something else wrong. If you are getting proper response when you directly hit the url in browser, then try doing the below when doing the ajax call. It passes the content type that is expecting back from the server.
function init() {
var url = "profile/getavatar";
$.ajax({
url : url,
dataType: "json"
}).then(function(data) {
avatarLink = data;
loadAvatar(avatarLink);
});
function loadAvatar(avatarLink){
$("#userAvatar").attr("src", avatarLink);
}
}
If you are using spring 4, Please make sure that you have Jakson jars in your dependency library. framework will automatically pickup the content negotiator as JSON and will find for the Jakson jars in the background to transport JSON to server and get JSON data back from server
use JAXB jars , in case you need to handle XML as content negotiator.