GET请求带header的请求方式

  • Post author:
  • Post category:其他


正常会有封装好的post方法,get方法带header可以用restTemplate的exchange()方法自己封装一个

使用:

String dcToken = "**";
        String centerFlag = "**";
        //header的值
        Map headers = new HashMap(4);
        headers.put("token",dcToken);
        headers.put("sign",centerFlag);
        //加入自己的url
        StringBuffer url = new StringBuffer("http://127.0.0.1:8080/***");
        //参数封组装
        for (Map.Entry<String, Object> key : param.entrySet()){
            url.append("&").append(key.getKey()).append("=").append(key.getValue());
        }
        //组装请求头
        HttpHeaders requestHeaders = this.buildHeaders(headers);
        HttpEntity<String> requestEntity = new HttpEntity(requestHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url.toString(),
                HttpMethod.GET, requestEntity, String.class, new Object[0]);

        JSONObject result = JSONObject.parseObject(response.getBody(), JSONObject.class);
        //这里根据具体情况提取自己需要的数据
        List<Map<String, Object>> data = (List<Map<String, Object>>)result.getJSONObject("RSP").get("DATA");

headers封装:

protected HttpHeaders buildHeaders(Map<String, String> headers) {
        HttpHeaders reqHeaders = new HttpHeaders();
        if (null != headers) {
            for (String key : headers.keySet()) {
                if (null == headers.get(key)) {
                    reqHeaders.add(key, "");
                }
                reqHeaders.add(key, headers.get(key));
            }
        }

        return reqHeaders;
    }

一些包:

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.RestTemplate;
import org.springframework.http.HttpMethod;

大概就这些的,如果没有描述清楚,可以留言问我



版权声明:本文为SELECT_BIN原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。