簡體   English   中英

將curl命令轉換為RestTemplate

[英]Convert curl command into RestTemplate

我有以下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 Bad請求

我確認Jackson的objectmapper正確序列化了對象objectMapper.writeValueAsString(Collections.singletonList(e))

我懷疑我無法正確處理--data-urlencode示例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);

對我來說很好:

這是帶有客戶端和請求的代碼,請忽略請求簽名

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:第一個請求會觸發你的代碼:

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

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

上面的請求將轉到服務層,其中代碼與您的代碼相同。


    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"]>
    }

然后再次控制器,只是檢查控制器是否接受來自調用者的String對象或Event對象。 這里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
    }

我認為唯一的問題是MediaType ,您發送的數據不是表單數據( APPLICATION_FORM_URLENCODED

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

請參閱關於RestTemplate詳細

暫無
暫無

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

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