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;
        }
  • 相关阅读:
    金刚经与心经之比较
    ECMWF 和 GFS 模型
    LSTM之父Jürgen Schmidhuber评图灵
    STM32相关知识点
    最全C++11/14/17/20/23 的新特性代码案例
    C++ 在线工具
    如何在 Proteus 中设计 PCB
    STM32电源框图解析
    【新特性速递】填一个坑
    【新特性速递】表格加载速度足足 3 倍提升,爱了爱了
  • 原文地址:https://www.cnblogs.com/zml-java/p/9226003.html
Copyright © 2011-2022 走看看