簡體   English   中英

將RequestParam數據傳遞給Spring RestController

[英]Passing RequestParam data to Spring RestController

我正在使用restTemplate.exchange方法從另一服務調用一個服務。我的請求URL確實接受了請求參數。

網址的格式為http://localhost:8035/sgapp/student/fetchDeptNo?sid

在管理員中,它寫為

@RestController
@RequestMapping(value="/sgapp/student")
public class SiController{
     @GetMapping(value = "/fetchDeptNo",consumes = "application/x-www-form-urlencoded")
      public ResponseEntity<String> getSid(@RequestParam(name = "sid")String sid){
                  String sid = myRepo.getSidCode(sid);
                  System.out.println("sid received from DB::"+sid); 
                  return new ResponseEntity<String>(sid,HttpStatus.OK);
              }
        }

在呼叫者應用程序中,我將其作為

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<?> entity = new HttpEntity<>(headers);
        Map paramMap = new HashMap<String, String>();
        paramMap.put("sid", sidData);
        HttpEntity<String> sidRespnse = restTemplate.exchange(
                "http://localhost:8035/sgapp/student/fetchDeptNo", HttpMethod.GET, entity, String.class,
                paramMap);

但是我遇到了以下異常:

org.springframework.web.client.HttpClientErrorException: 400 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]

誰能為此提供任何合適的解決方案???

該特定的exchange方法用於將變量替換為路徑。

如果要傳遞查詢參數,請使用UriComponentsBuilder創建帶有查詢參數的URL:

UriComponentsBuilder builder = 
    UriComponentsBuilder
        .fromHttpUrl(rootUri)
        .queryParam("sid", sidData);

然后,您可以使用RestTemplate,如下所示:

restTemplate.exchange(
    builder.toUriString(),
    HttpMethod.GET,
    entity,
    String.class);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM