• spring restTemplate 发送post请求携带参数和请求头


    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Service;
    import org.springframework.web.client.RestClientException;
    import org.springframework.web.client.RestTemplate;
    
    
    
    @Service
    @Slf4j
    public class TestServiceImpl implements TestService {
    
        @Autowired
        private RestTemplate restTemplate;
    
        private final String URL = "http://15.15.82.127:8124/api/test/getData";
    
        private final String USER_NAME = "test";
    
        private final String PASS_WORD = "test123";
    
        @Override
        public String getData(){
            //1、构建body参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("UserName",USER_NAME);
            jsonObject.put("Password",PASS_WORD);
    
            //2、添加请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type","application/json");
    
            //3、组装请求头和参数
            HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(jsonObject), headers);
    
            //4、发起post请求
            ResponseEntity<String> stringResponseEntity = null;
            try {
                stringResponseEntity = restTemplate.postForEntity(URL, formEntity, String.class);
                log.info("ResponseEntity----"+stringResponseEntity);
            } catch (RestClientException e) {
                e.printStackTrace();
            }
    
            //5、获取http状态码
            int statusCodeValue = stringResponseEntity.getStatusCodeValue();
            log.info("httpCode-----"+statusCodeValue);
    
            //6、获取返回体
            String body = stringResponseEntity.getBody();
            log.info("body-----"+body);
    
            //7、映射实体类
            Wrapper wrapper = JSONObject.parseObject(body, Wrapper.class);
            String data = wrapper.getData();
            log.info("data-----"+data);
    
            return data;
        }
    
    
    }
    
  • 相关阅读:
    linux c 链接详解3-静态库
    ubuntu下安装chrome谷歌浏览器
    零填充(Zero-padding)
    单例模式的多种写法(线程安全)
    执行代码出现ImportError:attempted relative import with no known parent package
    用anaconda安装tensorflow
    A* 算法的原理
    梯度消失(vanishing gradient)和梯度爆炸(exploding gradient)
    spark安装
    [转]虚拟机VMware3种网络模式(桥接、nat、Host-only)的工作原理
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/16020466.html
Copyright © 2020-2023  润新知