簡體   English   中英

帶有 URL 編碼數據的 Spring RestTemplate POST 請求

[英]Spring RestTemplate POST Request with URL encoded data

我是 Spring 的新手,正在嘗試使用 RestTemplate 進行休息請求。 Java 代碼應執行與以下 curl 命令相同的操作:

curl --data "name=feature&color=#5843AD" --header "PRIVATE-TOKEN: xyz" "https://someserver.com/api/v3/projects/1/labels"

但是服務器以400 Bad Request拒絕 RestTemplate

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> entity = new HttpEntity<String>("name=feature&color=#5843AD", headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.exchange("https://someserver.com/api/v3/projects/1/labels", HttpMethod.POST, entity, LabelCreationResponse.class);

有人可以告訴我我做錯了什么嗎?

我認為問題在於,當您嘗試將數據發送到服務器時,沒有設置應該是以下兩者之一的內容類型標頭:“application/json”或“application/x-www-form-urlencoded”。 在您的情況下是:“application/x-www-form-urlencoded”基於您的示例參數(名稱和顏色)。 此標頭的意思是“我的客戶端向服務器發送的數據類型”。

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name","feature");
map.add("color","#5843AD");

HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);

ResponseEntity<LabelCreationResponse> response =
    restTemplate.exchange("https://foo/api/v3/projects/1/labels",
                          HttpMethod.POST,
                          entity,
                          LabelCreationResponse.class);

您需要將 Content-Type 設置為 application/json。 Content-Type 必須在請求中設置。 下面是設置內容類型的修改代碼

final String uri = "https://someserver.com/api/v3/projects/1/labels";
String input = "US";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> request = new HttpEntity<String>(input, headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.postForObject(uri, request,  LabelCreationResponse.class);

在這里,HttpEntity 是用您的輸入(即“US”)和標頭構建的。 讓我知道這是否有效,如果無效,請分享異常。 干杯!

如果標頭是有效標頭,則可能是標頭問題檢查,您指的是“BasicAuth”標頭嗎?

HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
headers.add("Accept", MediaType.APPLICATION_JSON.toString()); //Optional in case server sends back JSON data
    
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<String, String>();
requestBody.add("name", "feature");
requestBody.add("color", "#5843AD");
    
HttpEntity formEntity = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);
    
ResponseEntity<LabelCreationResponse> response = 
   restTemplate.exchange("https://example.com/api/request", HttpMethod.POST, formEntity, LabelCreationResponse.class);

我的問題是, MessageConverters包含其他轉換器可能會將實體轉換為 json(如 FastJsonHttpMessageConverter)。 所以我將 FormHttpMessageConverter 添加到前面並且效果很好。

<T> JuheResult<T> postForm(final String url, final MultiValueMap<String, Object> body) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
    return exchange(url, HttpMethod.POST, requestEntity);
}

<T> JuheResult<T> exchange(final String url, final HttpMethod method, final HttpEntity<?> requestEntity) {
    ResponseEntity<JuheResult<T>> response = restTemplate.exchange(url, method, requestEntity,
            new JuheResultTypeReference<>());
    logger.debug("調用結果 {}", response.getBody());
    return response.getBody();
}

public JuheSupplierServiceImpl(RestTemplateBuilder restTemplateBuilder) {
    Duration connectTimeout = Duration.ofSeconds(5);
    Duration readTimeout = Duration.ofSeconds(5);

    restTemplate = restTemplateBuilder.setConnectTimeout(connectTimeout).setReadTimeout(readTimeout)
            .additionalInterceptors(interceptor()).build();
    restTemplate.getMessageConverters().add(0, new FormHttpMessageConverter());
}

fastjson 防止resttemplate轉換json以外的其他mediaType

暫無
暫無

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

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