programing

rest API에 여러 매개 변수 전달 - Spring

linuxpc 2023. 3. 7. 21:10
반응형

rest API에 여러 매개 변수 전달 - Spring

JSON 오브젝트를 rest API에 전달하거나 여러 파라미터를 해당 API에 전달하거나 봄철에 이들 파라미터를 읽는 방법이 가능한지 알아보려고 합니다.url이 다음 예시와 같다고 가정합니다.

예 1http://localhost:8080/api/v1/mno/objectKey?id=1&name=saif

아래 URL과 같이 JSON 오브젝트를 전달해도 될까요?

예 2http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}

질문:

1) JSON 오브젝트를 Ex.2와 같이 URL에 전달할 수 있습니까?

2) Ex.1의 파라미터는 어떻게 패스 및 해석할 수 있습니까?

목표를 달성하기 위해 몇 가지 방법을 쓰려고 했지만, 적절한 해결책을 찾을 수 없었습니다.

JSON 개체를 @RequestParam으로 전달하려고 했습니다.

http://localhost:8080/api/v1/mno/objectKey?id=1예기치 않은 오류가 발생했습니다.(type=Unsupported Media Type, status=415). Content type 'null' not supported

http://localhost:8080/api/v1/mno/objectKey/id=1예기치 않은 오류가 발생했습니다.(type=Not Found, status=404). No message available

http://localhost:8080/api/v1/mno/objectKey/%7B%22id%22:1%7D예기치 않은 오류가 발생했습니다.(type=Not Found, status=404). No message available

@RequestMapping(value="mno/{objectKey}",
                method = RequestMethod.GET, 
                consumes="application/json")
    public List<Book> getBook4(@RequestParam ObjectKey objectKey) {
        ...
    }

JSON 개체를 @PathVariable로 전달하려고 했습니다.

@RequestMapping(value="ghi/{objectKey}",method = RequestMethod.GET)
    public List<Book> getBook2(@PathVariable ObjectKey objectKey) {
        ...         
    }

id 파라미터 및 name 등의 기타 파라미터를 유지하기 위해 이 오브젝트를 만들었습니다.

class ObjectKey{
        long id;
        public long getId() {
            return id;
        }
        public void setId(long id) {
            this.id = id;
        }
    }

(1) JSON 오브젝트를 Ex.2와 같은 URL로 전달할 수 있습니까?

아니요, 왜냐하면http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}유효한 URL이 아닙니다.

RESTful 방식으로 하려면http://localhost:8080/api/v1/mno/objectKey/1/Saif는 다음과 같이 메서드를 정의했습니다.

@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
    // code here
}

(2) Ex.1의 파라미터는 어떻게 패스하고 해석할 수 있습니까?

두 개의 요청 매개 변수를 추가하고 올바른 경로를 지정하십시오.

@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
    // code here
}

갱신하다 (댓글에서)

만약 우리가 복잡한 파라미터 구조를 가지고 있다면?

"A": [ {
    "B": 37181,
    "timestamp": 1160100436,
    "categories": [ {
        "categoryID": 2653,
        "timestamp": 1158555774
    }, {
        "categoryID": 4453,
        "timestamp": 1158555774
    } ]
} ]

그것을 a로 송신합니다.POSTJSON 데이터를 URL이 아닌 요청 본문에 저장하고 다음 콘텐츠유형을 지정합니다.application/json.

@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
    // code here
}

다음과 같은 URL에서 여러 개의 매개 변수를 전달할 수 있습니다.

http://localhost:2000/custom?brand=custom&limit=20&price=20000&price=asc

이 쿼리 필드를 얻으려면 다음과 같은 맵을 사용합니다.

    @RequestMapping(method = RequestMethod.GET, value = "/custom")
    public String controllerMethod(@RequestParam Map<String, String> customQuery) {

        System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
        System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
        System.out.println("customQuery = price " + customQuery.containsKey("price"));
        System.out.println("customQuery = other " + customQuery.containsKey("other"));
        System.out.println("customQuery = sort " + customQuery.containsKey("sort"));

        return customQuery.toString();
    }

다음과 같이 여러 매개 변수를 지정할 수 있습니다.

    @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
    public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
      , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
               //logic
}

예. URL에서 JSON 개체를 전달할 수 있습니다.

queryString = "{\"left\":\"" + params.get("left") + "}";
 httpRestTemplate.exchange(
                    Endpoint + "/A/B?query={queryString}",
                    HttpMethod.GET, entity, z.class, queryString);

언급URL : https://stackoverflow.com/questions/38032635/pass-multiple-parameters-to-rest-api-spring

반응형