RestTemplate发送请求并携带header信息

简介: 1、使用restTemplate的postForObject方法   注:目前没有发现发送携带header信息的getForObject方法。 HttpHeaders headers = new HttpHeaders(); Enumeration headerNames = request.

1、使用restTemplate的postForObject方法

  注:目前没有发现发送携带header信息的getForObject方法。

HttpHeaders headers = new HttpHeaders();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
  String key = (String) headerNames.nextElement();
  String value = request.getHeader(key);
  headers.add(key, value);
}        
String restStrResult = restTemplate.postForObject(url, /*携带header*/new HttpEntity<String>(headers), String.class,
             /*携带parameter*/request.getParameterMap());

2、使用restTemplate

import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestTemplateUtil {
    
    private RestTemplate restTemplate;
    
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String post(ServletRequest req, String url, Map<String, ?> params) {
        ResponseEntity<String> rss = request(req, url, HttpMethod.POST, params);
        return rss.getBody();
    }

    public String get(ServletRequest req, String url, Map<String, ?> params) {
        ResponseEntity<String> rss = request(req, url, HttpMethod.GET, params);
        return rss.getBody();
    }
    
    public String delete(ServletRequest req, String url, Map<String, ?> params) {
        ResponseEntity<String> rss = request(req, url, HttpMethod.DELETE, params);
        return rss.getBody();
    }
    
    public String put(ServletRequest req, String url, Map<String, ?> params) {
        ResponseEntity<String> rss = request(req, url, HttpMethod.PUT, params);
        return rss.getBody();
    }
    
    /**
     * @param req
     * @param url
     * @param method
     * @param params maybe null
     * @return
     */
    private ResponseEntity<String> request(ServletRequest req, String url, HttpMethod method, Map<String, ?> params) {
        HttpServletRequest request = (HttpServletRequest) req;
        //获取header信息
        HttpHeaders requestHeaders = new HttpHeaders();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
          String key = (String) headerNames.nextElement();
          String value = request.getHeader(key);
          requestHeaders.add(key, value);
        }
        //获取parameter信息
        if(params == null) {
            params = request.getParameterMap();
        }
        
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
        ResponseEntity<String> rss = restTemplate.exchange(url, method, requestEntity, String.class, params);
        return rss;
    }
}

 3.restTemplate以json格式发送post请求

  1.发送请求

  public String _post(ServletRequest req, String url, Map<String, ?> params) {
        HttpServletRequest request = (HttpServletRequest) req;
        //拿到header信息
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
          String key = (String) headerNames.nextElement();
          String value = request.getHeader(key);
          requestHeaders.add(key, value);
        }
        net.sf.json.JSONObject jsonParams = net.sf.json.JSONObject.fromObject(params);
        HttpEntity<net.sf.json.JSONObject> requestEntity = new HttpEntity<net.sf.json.JSONObject>(jsonParams, requestHeaders);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        return result;
    }

  2.接收处理

   @RequestMapping("/xxx")  
    @ResponseBody  
    public String xxx(HttpServletRequest request) throws IOException {  
  
        String jsonString = getBodyString(request.getReader());  
  
        JSONObject jbJsonObject = new JSONObject().fromObject(jsonString);  
  
        User user = (User) JSONObject.toBean(jbJsonObject, User.class);  
        System.out.println(jbJsonObject);  
        System.out.println("id:" + user.getUserName());return null;  
  
    }  
  
    @RequestMapping("/xxx2")  
    @ResponseBody  
    public String xxx2(User user) throws IOException {  
  
        System.out.println("---------------");  
        System.out.println(user.getUserName());  
        System.out.println(user.getPassWord());  
        System.out.println("---------------");  
  
        if (true) {  
            return "success";  
        } else {  
            return "fail";  
        }  
  
    }  

  
  public String getBodyString(BufferedReader br) { 
    String inputLine; 
    String str = ""; 
    try { 
      while ((inputLine = br.readLine()) != null) { 
      str += inputLine; 
    } 
      br.close(); 
    } catch (IOException e) { 
      System.out.println("IOException: " + e); 
    } 
    return str; 
  }

 

4. RestTemplate 的两个 postForObject方法的使用

  private static String post(String url, JSONObject params, MediaType mediaType) {
        RestTemplate restTemplate = new RestTemplate();
        //拿到header信息
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(mediaType);
        HttpEntity<JSONObject> requestEntity = (mediaType == MediaType.APPLICATION_JSON || mediaType == MediaType.APPLICATION_JSON_UTF8) ? 
                new HttpEntity<JSONObject>(params, requestHeaders) : new HttpEntity<JSONObject>(null, requestHeaders);
        restTemplate.setErrorHandler(new ResponseErrorHandler() {
            
            @Override
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getStatusCode().value() != HttpServletResponse.SC_OK;
            }
            
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
                String str = null;
                while((str = br.readLine()) != null) {
                    System.out.println(str);
                }
            }
        });
        String result = (mediaType == MediaType.APPLICATION_JSON || mediaType == MediaType.APPLICATION_JSON_UTF8)  ? 
                restTemplate.postForObject(url, requestEntity, String.class) : restTemplate.postForObject(expandURL(url, params.keySet()), requestEntity, String.class, params);
        return result;
    }
    
    
    private static String expandURL(String url, Set<?> keys){
        final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
        Matcher mc = QUERY_PARAM_PATTERN.matcher(url);
        StringBuilder sb = new StringBuilder(url);
        if(mc.find()) {
            sb.append("&");
        } else {
            sb.append("?");
        }
        
        for(Object key : keys) {
            sb.append(key).append("=").append("{").append(key).append("}").append("&");
        }
        return sb.deleteCharAt(sb.length()-1).toString();
    }

 

5.最强版RestTemplateUtils

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Title: RestTemplateUtils.java
 * @Prject: sensorsdata
 * @Package: com.springboottest.sensorsdata.utils
 * @Description: TODO
 * @author: hujunzheng
 * @date: 2017年4月20日 下午2:07:18
 * @version: V1.0
 */
public class RestTemplateUtils {

    /**
     * @ClassName: DefaultResponseErrorHandler
     * @Description: TODO
     * @author: hujunzheng
     * @date: 2017年4月20日 下午2:15:27
     */
    private static class DefaultResponseErrorHandler implements ResponseErrorHandler {

        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            return response.getStatusCode().value() != HttpServletResponse.SC_OK;
        }

        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
            StringBuilder sb = new StringBuilder();
            String str = null;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            try {
                throw new Exception(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param url
     * @param params
     * @return
     * @Title: get
     * @author: hujunzheng
     * @Description: TODO
     * @return: String
     */
    public static String get(String url, JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        String response = restTemplate.getForObject(expandURL(url, params.keySet()), String.class, params);
        return response;
    }

    /**
     * @param url
     * @param params
     * @param mediaType
     * @return
     * @Title: post
     * @author: hujunzheng
     * @Description: 将参数都拼接在url之后
     * @return: String
     */
    public static String post(String url, JSONObject params, MediaType mediaType) {
        RestTemplate restTemplate = new RestTemplate();
        // 拿到header信息
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(mediaType);
        HttpEntity<JSONObject> requestEntity = (mediaType == MediaType.APPLICATION_JSON
                || mediaType == MediaType.APPLICATION_JSON_UTF8) ? new HttpEntity<JSONObject>(params, requestHeaders)
                : new HttpEntity<JSONObject>(null, requestHeaders);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        String result = (mediaType == MediaType.APPLICATION_JSON || mediaType == MediaType.APPLICATION_JSON_UTF8)
                ? restTemplate.postForObject(url, requestEntity, String.class)
                : restTemplate.postForObject(expandURL(url, params.keySet()), requestEntity, String.class, params);
        return result;
    }


    /**
     * @param url
     * @param params
     * @param mediaType
     * @param clz
     * @return
     * @Title: post
     * @author: hujunzheng
     * @Description: 发送json或者form格式数据
     * @return: String
     */
    public static <T> T post(String url, JSONObject params, MediaType mediaType, Class<T> clz) {
        RestTemplate restTemplate = new RestTemplate();
        //这是为 MediaType.APPLICATION_FORM_URLENCODED 格式HttpEntity 数据 添加转换器
        //还有就是,如果是APPLICATION_FORM_URLENCODED方式发送post请求,
        //也可以直接HttpHeaders requestHeaders = new HttpHeaders(createMultiValueMap(params),true),就不用增加转换器了
        restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
        // 设置header信息
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(mediaType);

        HttpEntity<?> requestEntity = (
                mediaType == MediaType.APPLICATION_JSON
                        || mediaType == MediaType.APPLICATION_JSON_UTF8)
                ? new HttpEntity<JSONObject>(params, requestHeaders)
                : (mediaType == MediaType.APPLICATION_FORM_URLENCODED
                    ? new HttpEntity<MultiValueMap>(createMultiValueMap(params), requestHeaders)
                    : new HttpEntity<>(null, requestHeaders));

        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        T result = (mediaType == MediaType.APPLICATION_JSON || mediaType == MediaType.APPLICATION_JSON_UTF8)
                ? restTemplate.postForObject(url, requestEntity, clz)
                : restTemplate.postForObject(mediaType == MediaType.APPLICATION_FORM_URLENCODED
                    ? url
                    : expandURL(url, params.keySet()), requestEntity, clz, params);

        return result;
    }

    private static MultiValueMap<String, String> createMultiValueMap(JSONObject params) {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        for(String key : params.keySet()) {
            if(params.get(key) instanceof List) {
                for(Iterator<String> it=((List<String>) params.get(key)).iterator(); it.hasNext(); ) {
                    String value = it.next();
                    map.add(key, value);
                }
            } else {
                map.add(key, params.getString(key));
            }
        }
        return map;
    }

    /**
     * @param url
     * @param keys
     * @return
     * @Title: expandURL
     * @author: hujunzheng
     * @Description: TODO
     * @return: String
     */
    private static String expandURL(String url, Set<?> keys) {
        final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
        Matcher mc = QUERY_PARAM_PATTERN.matcher(url);
        StringBuilder sb = new StringBuilder(url);
        if (mc.find()) {
            sb.append("&");
        } else {
            sb.append("?");
        }

        for (Object key : keys) {
            sb.append(key).append("=").append("{").append(key).append("}").append("&");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }
}

 

目录
相关文章
|
JSON Java API
玩转Spring Boot之RestTemplate的使用
在java代码里想要进行restful web client服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。Spring Boot提供了一种简单便捷的内置模板类来进行操作,这就是RestTemplate。
6172 0
五分钟带你玩转sonar(五)教你使用SonarLint插件
五分钟带你玩转sonar(五)教你使用SonarLint插件
5199 0
五分钟带你玩转sonar(五)教你使用SonarLint插件
|
前端开发 Java 数据安全/隐私保护
用户登录前后端开发(一个简单完整的小项目)——SpringBoot与session验证(带前后端源码)全方位全流程超详细教程
文章通过一个简单的SpringBoot项目,详细介绍了前后端如何实现用户登录功能,包括前端登录页面的创建、后端登录逻辑的处理、使用session验证用户身份以及获取已登录用户信息的方法。
1791 2
用户登录前后端开发(一个简单完整的小项目)——SpringBoot与session验证(带前后端源码)全方位全流程超详细教程
|
9月前
|
存储 缓存 自然语言处理
智能客服进阶:基于DeepSeek与PHP的多轮对话与上下文管理
本文基于前文构建的DeepSeek和PHP智能客服系统,深入探讨了多轮对话与上下文管理的实现。通过维护会话状态(如使用PHP的`$_SESSION`),系统能记住对话历史,提供连贯的回答。具体案例展示了如何处理书籍推荐及后续查询,如“这本书的作者是谁”。此外,还介绍了优化方向,包括实体识别、对话策略调整和持久化存储,以提升智能客服的复杂需求处理能力。
|
人工智能 自然语言处理 数据挖掘
RAG 系统高效检索提升秘籍:如何精准选择 BGE 智源、GTE 阿里与 Jina 等的嵌入与精排模型的完美搭配
RAG 系统高效检索提升秘籍:如何精准选择 BGE 智源、GTE 阿里与 Jina 等的嵌入与精排模型的完美搭配
RAG 系统高效检索提升秘籍:如何精准选择 BGE 智源、GTE 阿里与 Jina 等的嵌入与精排模型的完美搭配
|
Java UED Spring
Springboot通过SSE实现实时消息返回
通过Spring Boot实现SSE,可以简单高效地将实时消息推送给客户端。虽然SSE有其限制,但对于许多实时消息推送场景而言,它提供了一种简洁而强大的解决方案。在实际开发中,根据具体需求选择合适的技术,可以提高系统的性能和用户体验。希望本文能帮助你深入理解Spring Boot中SSE的实现和应用。
5689 1
|
监控 Java 开发者
什么是 Spring Boot?
什么是 Spring Boot?
2725 6
|
开发工具 git
IDEA更改远程git仓库地址
【9月更文挑战第27天】本文介绍了两种在IntelliJ IDEA中更改远程Git仓库地址的方法:一是通过图形界面,在VCS设置中直接修改;二是通过IDEA内置的命令行工具使用`git`命令进行更改。具体步骤包括从版本控制菜单进入项目设置、修改远程仓库URL,以及使用`git remote set-url`命令更新仓库地址,并验证修改结果。这些方法适用于项目迁移或更换仓库地址的情况。
2728 6
|
Java Spring
SpringBoot 项目打成 jar 后,如何加载外部的配置文件?
SpringBoot 项目打成 jar 后,如何加载外部的配置文件?
1841 0