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;
        }
  • 相关阅读:
    UML基础—结构和组成
    Hadoop完全分布式
    Hadoop完全分布式
    查看端口是否启用
    查看端口是否启用
    hadoop namenode启动失败
    hadoop namenode启动失败
    Hadoop2.7.5伪分布式安装
    Hadoop2.7.5伪分布式安装
    给用户添加sudo权限
  • 原文地址:https://www.cnblogs.com/zml-java/p/9226003.html
Copyright © 2011-2022 走看看