簡體   English   中英

帶有查詢參數的 RestTemplate POST 沒有請求正文

[英]RestTemplate POST with query parameter without request body

我正在嘗試使用 RestTemplate 的 POST 方法。 我需要我的請求只有 1 個查詢參數,沒有正文(例如localhost:8080/predictions/init?date=xxxx )。

我目前的代碼如下:

String url = "http://localhost:8080/predictions/init";
String dateToGenerate = "xxxx";

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
Map map = new HashMap<String, String>();
map.put("Content-Type", "application/json");
headers.setAll(map);

Map req_payload = new HashMap();
req_payload.put("date", dateToGenerate);

HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
restTemplateApi.postForEntity(url, request, String.class);

我試圖調用的 REST 控制器的一側如下:

 @PostMapping
 @ResponseStatus(HttpStatus.OK)
 public PredictionGenerated initializeOnePrediction(@RequestParam @NotEmpty String date) { 
      .............................
      .............................
 }

我目前收到org.springframework.web.client.HttpClientErrorException: 400 null

有任何想法嗎?

如果您有許多查詢參數,則在多值映射中設置所有參數,如下所示。

MultiValueMap<String, String> param= new 
LinkedMultiValueMap<String, String>();
param.put("date", datevalue);

然后創建 Http 頭添加所需的內容。

HttpHeaders headers = new HttpHeaders()
header.setContentType("application/json");

創建如下 URL。

URI  url = UriComponentsBuilder.fromHttpUrl(base url)
    .queryParams(param)
    .build();

HttpEntity<?> request = new HttpEntity<>(req_payload, 
headers);
restTemplateApi.postForEntity(url, request, String.class);

暫無
暫無

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

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