简体   繁体   中英

Spring Controller GET/POST/PUT to another interface

I am using React as frontend and Java Spring Boot as backend. React sends JSON form data as GET/PUT/POST requests to my backend url (http://localhost:8080/test). Now, I wan't to send this JSON forward to another interfaces GET endpoint (https://another/interface/add?id={id}). This interface then queries database based on the id and answers 200 OK message with a JSON reply which I need to display (send back to frontend).

1. What is the correct way of sending a request to another interface from Spring Boot backend? In the same method I catched the frontends data?
2. I also have to set HTTP headers to the GET request, how would I go on about this?

Example of how Frontend is sending an id field as a JSON to backend:
React POST

    addId = async (data) => {
        return this.post(/localhost:8080/test/id, data)
    }

Example of how Backend is receiving the id field:
Spring Boot POST

    @PostMapping("test/id")
    public String test(@RequestBody String id) {
        return id;
    }

As I understand you want to get data from backend with json body and httpstatuscode 200. Am i right?

May be you can try this

@GetMapping(/interface/add)
public ResponseEntity<?> test(@RequestParam("id") String id){
  //write code you want
return ResponseEntity.status(HttpStatus.OK).body("string" or dto possible);
}

ResponseEntity send body with httpstatus code and if you want to send requestparam you set @RequestParam annotation to set.

  1. When I do project with springboot and react. I use json type to exchange data. And Most Services usually exchange data with json data type.

2.I confused about this Question if you send data React to springboot your code is right Axios.get("localhost....", data) you can change http type with Axios.(get, post, delete)

Hi to answer both of your questions, you shall use Webclient which comes as a part of spring Web reactive module. Read more about it here. https://www.baeldung.com/spring-5-webclient

Since your requirement is to have some other interface with a different host (I assume) you can have a separate springboot server just dedicatedly running for that purpose and you can make outbound requests from your existing spring boot backend application to that. You can also view about how you can attach headers to outbound requests in the same link that I have mentioned above.

PS: i wouldn't recommend having a interface within your existing springboot application itself. If you wanna do so it can support that too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM