• RestTemplate的HTTP传输


    Post请求

    Post的postForObject和postForEntity区别

    • postForObject()返回值是HTTP协议的响应体。
    • postForEntity()返回的是ResponseEntity,ResponseEntity是对HTTP响应的封装,除了包含响应体,还包含HTTP状态码、contentType、contentLength、Header等信息。

    代码one

     RestTemplate restTemplate = new RestTemplate();
            // 请求头设置,x-www-form-urlencoded格式的数据
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("access_key", v.getAccess_key());
            map.add("format", v.getFormat());
            map.add("sign", v.getSign());
            map.add("timestamp", v.getTimestamp());
            map.add("biz_content", v.getBiz_content());
            log.info("标准接口地址传出" + map);
            OutResponse result = restTemplate.postForObject(url, map, OutResponse.class);
            log.info("标准接口地址传入" + result);
    

    代码two

     RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Object> requestEntity = new HttpEntity<>(refundRequest, headers);
            log.info("标准接口退款传出参数" + refundRequest);
            ResponseEntity<RefundResponse> responsee = restTemplate.exchange(refundUrl, HttpMethod.POST, requestEntity, RefundResponse.class);
            log.info("标准接口退款传入参数" + responsee.getBody());
            HashMap<String,String> hashMap=new HashMap<>();
    

    注意

    headers.setContentType()方法一个是以请求体方式提交,一个是以表单方式提交;同时以表单提交一定要使用LinkedMultiValueMap的map实现类,不能使用实体类。

    Get请求

    代码

    • Restful风格
    String url = "http://jsonplaceholder.typicode.com/{1}/{2}";
    PostDTO postDTO = restTemplate.getForObject(url, PostDTO.class, "1", "2");
    
    • 普通风格
    Map<String, String> params = new HashMap<>();
    params.put("name", "dada");
    restTemplate.getForEntity("http://HELLO-SERVICE/hello1?name={name}", String.class, params);
    
  • 相关阅读:
    Go 语言基础知识
    Docker 配置代理
    Kubernetes StatefulSets
    Kubernetes Storage
    Centos7.4 Nginx反向代理+负载均衡配置
    LVS 负载均衡原理详解
    Kubernetes Ingress
    Kubernetes Endpoints
    kubernetes 核心对象
    K8s ipvs mode kube-proxy
  • 原文地址:https://www.cnblogs.com/xiaofengshan/p/16074499.html
Copyright © 2020-2023  润新知