简体   繁体   English

将curl命令转换为RestTemplate

[英]Convert curl command into RestTemplate

I have the following curl expression: 我有以下curl表达式:

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

which should be converted into RestTemplate.postForEntity call. 应该转换为RestTemplate.postForEntity调用。 I do conversion this way: 我这样做转换:

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);

Server returns 400 Bad request 服务器返回400 Bad请求

I confirm that Jackson's objectmapper serializes the object correctly objectMapper.writeValueAsString(Collections.singletonList(e)) 我确认Jackson的objectmapper正确序列化了对象objectMapper.writeValueAsString(Collections.singletonList(e))

I suspect that I cannot correctly handle the mix of --data and --data-urlencode from example curl in RestTemplate. 我怀疑我无法正确处理--data-urlencode示例curl的--data--data-urlencode的混合。

Could you please suggest what am I doing wrong? 你能告诉我我做错了什么吗?

  // 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);

Works fine for me: 对我来说很好:

Here is the code with client and request, please ignore request signatures 这是带有客户端和请求的代码,请忽略请求签名

curl -X GET \
  http://localhost:8080/article/so \
  -H 'cache-control: no-cache' \
  -d 'api_key=API_Key&event=%5B%7B%22user_id%22%3A%2212345%22%2C%20%22event_type%22%3A%22buy_song%22%7D%5D'

controller: First request will trigger your code: controller:第一个请求会触发你的代码:

// This is just to trigger, you can ignore it.

    @RequestMapping(value = "/article/so", method = RequestMethod.GET)
    public void addArticle1() throws UnsupportedEncodingException, JsonProcessingException {
        articleServiceImpl.test();
    }

Above request will go to service layer where code is same as of yours. 上面的请求将转到服务层,其中代码与您的代码相同。


    public void test() throws JsonProcessingException, UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        Event e = new Event();
        e.setEvent_type("buy_song");
        e.setUser_id("12345");

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

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/article/so", request, String.class);
        System.out.println(response);//<200,[Content-Length:"0", Date:"Fri, 31 May 2019 09:26:24 GMT"]>
    }

Then the controller again, just to check whether controller accepts String object or Event object from the caller. 然后再次控制器,只是检查控制器是否接受来自调用者的String对象或Event对象。 Here Event is passed as URLEncodedString, which I am getting here as output. 这里Event作为URLEncodedString传递,我在这里作为输出。

    @RequestMapping(value = "/article/so", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void addArticle2(@RequestParam String api_key,@RequestParam String event) {
        System.out.println(api_key); // API_Key
        System.out.println(event); // %5B%7B%22user_id%22%3A%2212345%22%2C%22event_type%22%3A%22buy_song%22%7D%5D
    }

I think the only problem is MediaType , Data which you are sending is not form Data ( APPLICATION_FORM_URLENCODED ) 我认为唯一的问题是MediaType ,您发送的数据不是表单数据( APPLICATION_FORM_URLENCODED

It's json data so you need to use MediaType.APPLICATION_JSON Something like this 这是json数据,所以你需要使用MediaType.APPLICATION_JSON东西

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

// converting form variable to Map
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("api_key", "API_Key");
map.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// finally build Request
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity(
  apiUrl, request , String.class);

Refer this for more detail on RestTemplate 请参阅关于RestTemplate详细

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM