복붙노트

[SPRING] Spring RestTemplate으로 배열을 보내는 법?

SPRING

Spring RestTemplate으로 배열을 보내는 법?

Spring RestTemplate으로 배열 매개 변수를 보내려면 어떻게해야합니까?

이것은 서버 측 구현입니다.

@RequestMapping(value = "/train", method = RequestMethod.GET)
@ResponseBody
public TrainResponse train(Locale locale, Model model, HttpServletRequest request, 
    @RequestParam String category,
    @RequestParam(required = false, value = "positiveDocId[]") String[] positiveDocId,
    @RequestParam(required = false, value = "negativeDocId[]") String[] negativeDocId) 
{
    ...
}

이것이 제가 시도한 것입니다 :

Map<String, Object> map = new HashMap<String, Object>();
map.put("category", parameters.getName());
map.put("positiveDocId[]", positiveDocs); // positiveDocs is String array
map.put("negativeDocId[]", negativeDocs); // negativeDocs is String array
TrainResponse response = restTemplate.getForObject("http://localhost:8080/admin/train?category={category}&positiveDocId[]={positiveDocId[]}&negativeDocId[]={negativeDocId[]}", TrainResponse.class, map);

다음은 분명히 잘못된 실제 요청 URL입니다.

http://localhost:8080/admin/train?category=spam&positiveDocId%5B%5D=%5BLjava.lang.String;@4df2868&negativeDocId%5B%5D=%5BLjava.lang.String;@56d5c657`

검색을 시도했지만 해결 방법을 찾을 수 없습니다. 모든 포인터는 감사하겠습니다.

해결법

  1. ==============================

    1.Spring의 UriComponentsBuilder는 트릭을 수행하고 가변 확장을 허용합니다. 경로 변수가있는 URI 만 가진 리소스에 param "attr"으로 문자열 배열을 전달하려고한다고 가정합니다.

    Spring의 UriComponentsBuilder는 트릭을 수행하고 가변 확장을 허용합니다. 경로 변수가있는 URI 만 가진 리소스에 param "attr"으로 문자열 배열을 전달하려고한다고 가정합니다.

    UriComponents comp = UriComponentsBuilder.fromHttpUrl(
        "http:/www.example.com/widgets/{widgetId}").queryParam("attr", "width", 
            "height").build();
    UriComponents expanded = comp.expand(12);
    assertEquals("http:/www.example.com/widgets/12?attr=width&attr=height", 
       expanded.toString());
    

    그렇지 않으면 런타임에 확장해야하는 URI를 정의해야하고 미리 배열의 크기를 모를 경우 http://tools.ietf.org/html/rfc6570 UriTemplate에 {? key *} 자리 표시자를 만들고 https://github.com/damnhandy/Handy-URI-Templates에서 UriTemplate 클래스로 확장합니다.

    UriTemplate template = UriTemplate.fromTemplate(
        "http://example.com/widgets/{widgetId}{?attr*}");
    template.set("attr", Arrays.asList(1, 2, 3));
    String expanded = template.expand();
    assertEquals("http://example.com/widgets/?attr=1&attr=2&attr=3", 
        expanded);
    

    자바 이외의 언어에 대해서는 https://code.google.com/p/uri-templates/wiki/ 구현을 참조하십시오.

  2. ==============================

    2.나는 컬렉션을 반복하면서 URL을 구성했다.

    나는 컬렉션을 반복하면서 URL을 구성했다.

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("category", parameters.getName());
    
    String url = "http://localhost:8080/admin/train?category={category}";
    if (positiveDocs != null && positiveDocs.size() > 0) {
        for (String id : positiveDocs) {
            url += "&positiveDocId[]=" + id;
        }
    }
    if (negativeDocId != null && negativeDocId.size() > 0) {
        for (String id : negativeDocId) {
            url += "&negativeDocId[]=" + id;
        }
    }
    
    TrainResponse response = restTemplate.getForObject(url, TrainResponse.class, map);
    
  3. ==============================

    3.이 시도

    이 시도

    에서 요청 매핑 변경

    @RequestMapping(value = "/train", method = RequestMethod.GET)
    

     @RequestMapping(value = "/train/{category}/{positiveDocId[]}/{negativeDocId[]}", method = RequestMethod.GET)
    

    restTemplate에있는 귀하의 URL

    아래 주어진 형식으로 UR1을 변경하십시오

    http://localhost:8080/admin/train/category/1,2,3,4,5/6,7,8,9
    
  4. ==============================

    4.여기 내가 어떻게 그것을 달성했습니다 :

    여기 내가 어떻게 그것을 달성했습니다 :

    REST 컨트롤러 :

    @ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public ResponseEntity<Response> getPublicationSkus(
           @RequestParam(value = "skus[]", required = true) List<String> skus) {
        ...
    }
    

    요청 :

    List<String> skus = Arrays.asList("123","456","789");
    
    Map<String, String> params = new HashMap<>();
    params.put("skus", toPlainString(skus));
    
    Response response = restTemplate.getForObject("http://localhost:8080/test?skus[]={skus}", 
                                          Response.class, params);
    

    그런 다음 List 또는 String []을 쉼표로 구분 된 일반 문자열로 변환하는 메서드를 구현해야합니다. 예를 들어 Java 8에서는 다음과 같이됩니다.

    private static String toPlainString(List<String> skus) {
        return skus.stream().collect(Collectors.joining(","));
    }
    
  5. from https://stackoverflow.com/questions/14153036/how-to-send-array-with-spring-resttemplate by cc-by-sa and MIT license