zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    MySQL协议分析(2)
    MySQL协议分析(1)
    《汇编语言》知识重点总结
    opencv学习(1.2)
    CentOS 6下OpenCV的安装与配置
    python2与python3之间的主要区别
    python-PEP8编码规范
    解决windows 10无法打开.hlp帮助文件的问题
    将windows server 2016改造为像windows 10一样适合个人使用的系统
    系统分析师成长之路
  • 原文地址:https://www.cnblogs.com/zml-java/p/9226003.html
Copyright © 2011-2022 走看看