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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值