Home > Back-end >  Spring Boot : Adding query parameters to url on http request
Spring Boot : Adding query parameters to url on http request

Time:02-08

I was looking at a few post regrading query parameters in my url and I couldn't quite find what I was looking for.

So far the external api I am fetching data from requires a specific I will call in this case "tag" parameter when making http request in the browser.

Here is my Post model with a tag defined as a field

package com.example.blog.post;

import javax.persistence.*;

@Entity
@Table(name = "post")
public class Post{

    @Id
    @GeneratedValue
    private Long id;


    private String tag;

    public Post() {

    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {

        return id;
    }

    public String getTag() {
        return tag;
    }
}

And here is my controller class and the "getPosts()" method is where I am fetching the external data but it requires a tag parameter (query parameter) in order to complete the response. How do I incorporate the "tag" query parameter in this case?

package com.example.blog.post;

import org.springframework.web.bind.annotation.*;
import java.util.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.example.blog.HttpRequest;



@RestController
@RequestMapping
public class PostController {

    private PostRepository postRepository;

    private RestTemplate restTemplate;

//    @GetMapping("/api/ping")
//    public ResponseEntity<?> ping(){
//        String res = request.body();
//        return new ResponseEntity<>(res,HttpStatus.OK);
//    }



    @GetMapping("/api/posts")
    public ResponseEntity<?> getPosts(@RequestParam(value="tag") String tag){
        try{
            HttpRequest request = HttpRequest.get("https://api.blogs.io/blog/posts").connectTimeout(12000);
            String res = request.body();
            return new ResponseEntity<>(res,HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>("Error!,please try again",HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }



}

CodePudding user response:

Simply change your method to

@GetMapping("/api/posts")
public ResponseEntity<?> getPosts(@RequestParam("tag") String tag){...}

Then you also need to send that query param in url like

http://localhost:8080/api/posts?tag=java

CodePudding user response:

The tag request parameter should be sent to the url. And your getPosts() method tag parameter should be correct as follows.

getPosts(@RequestParam String tag)

value field is used in @RequestAttribute

  •  Tags:  
  • Related