在 HTTP 请求中向 URL 添加查询参数

Adding query parameters to URL on HTTP request

我在 URL 中查看了一些 post 重新分级查询参数,但我无法完全找到我要找的东西。

到目前为止,我从中获取数据的外部 API 需要一个特定的,在这种情况下,我将在浏览器中发出 HTTP 请求时调用“标记”参数。

这是我的 Post 模型,其中的标签定义为字段

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;
    }
}

这是我的控制器 class,“getPosts()”方法是我获取外部数据的地方,但它需要一个标记参数(查询参数)才能完成响应。在这种情况下如何合并“标签”查询参数?

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);
        }
    }
}

tag 请求参数应该发送到 url。并且您的 getPosts() 方法标记参数应该如下所示正确。

getPosts(@RequestParam String tag)

值字段用于 @RequestAttribute

只需将您的方法更改为

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

然后您还需要在 url 中发送该查询参数,例如

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