java - 将curl命令转换为RestTemplate

标签 java spring curl resttemplate urlencode

我有以下 curl 表达式:

curl --data 'api_key=API_Key' --data-urlencode 'event=[{"user_id":"12345", "event_type":"buy_song"}]' https://someapi

应将其转换为 RestTemplate.postForEntity 调用。我这样进行转换:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("api_key", "API_Key");
params.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// send
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity("https://someapi", request, String.class);

服务器返回400错误请求

我确认 Jackson 的 objectmapper 正确序列化了对象 objectMapper.writeValueAsString(Collections.singletonList(e))

我怀疑我无法正确处理 RestTemplate 中示例curl 中的 --data--data-urlencode 的混合。

你能建议我做错了什么吗?

最佳答案

  // org.apache.commons.collections.map.HashedMap     
  HashedMap requestBody = new HashedMap();
      requestBody.put("api_key", "API_Key");
      requestBody.put("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));   

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
       String jsonBody = new ObjectMapper().writeValueAsString(requestBody);
       HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

        ResponseEntity<String> response = restTemplate.postForEntity("https://someapi", entity, String.class);

关于java - 将curl命令转换为RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56391225/

相关文章:

java - 使用 Java 中的服务帐户进行 LDAP 身份验证

java - 客户端服务器应用+java

java - 使用 OData v4 语法解析器

Java:spring:为什么Abstract BeanFactory不允许更改父BeanFactory?

java - 如何防止在 TextArea 中输入也触发按键绑定(bind)?

java - 使用注释和属性文件中定义的类型的 Spring Autowiring ?

Spring Batch 重试策略和跳过策略问题

php - 避免box xpath和curl的头部

java - curl 或 HTTPRequest

php - 避免 cURL 调用之间的网络问题