MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            map.add("auditParams",auditJob.getAuditParams());

JSONObject jsonTaskObj = restTemplatePost(map);

 

 

public JSONObject restTemplatePost(MultiValueMap<String, Object> params) throws JSONException {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");

        String username = auditScriptConfig.getUsername();
        String password = auditScriptConfig.getPassword();
        String plainCredentials = username + ":" + password;
        String base64Credentials = Base64.getEncoder().encodeToString(plainCredentials.getBytes());

        httpHeaders.setContentType(mediaType);
        httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        //身份验证
        httpHeaders.add("Authorization", "Basic " + base64Credentials);

        //如果使用HttpEntity<JSONObject>对象传入很容易出现no suitable HttpMessageConverter found for request type的错误,直接转成字符串,JSONObject.toString()
        //HttpEntity<String> httpEntity = new HttpEntity<>(params, httpHeaders);
        //ResponseEntity<String> response = restTemplate.exchange(auditScriptConfig.getUrl(), HttpMethod.POST, httpEntity, String.class);


        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(params, httpHeaders);
        ResponseEntity<String> response = restTemplate.postForEntity(auditScriptConfig.getUrl(), httpEntity, String.class);

        HttpStatus status = response.getStatusCode();

        System.out.println("HttpStatus: "+ status);

        JSONObject result = new JSONObject(response.getBody());

        return result;
    }

 

相关文章:

  • 2021-07-10
  • 2021-10-19
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
  • 2021-04-10
  • 2021-06-15
  • 2021-05-25
猜你喜欢
  • 2021-08-29
  • 2022-01-19
  • 2021-01-29
  • 2021-10-27
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案