Spring RestTemplate post

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;
    }
原文地址:https://www.cnblogs.com/zml-java/p/9226003.html