zoukankan      html  css  js  c++  java
  • RestTemplate的异步使用

    参考:https://blog.csdn.net/yezhuanxu/article/details/53643248

    支持异步调用AsyncRestTemplate

    @RequestMapping("/async")
        public String asyncReq(){
            String url = "http://localhost:8080/jsonAsync";
            ListenableFuture<ResponseEntity<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class);
            future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() {
                public void onSuccess(ResponseEntity<JSONObject> result) {
                    System.out.println(result.getBody().toJSONString());
                }
            }, new FailureCallback() {
                public void onFailure(Throwable ex) {
                    System.out.println("onFailure:"+ex);
                }
            });
            return "this is async sample";
        }

    post请求如何自定义header

    @RequestMapping("/headerApi")//模拟远程的restful API
        public JSONObject withHeader(@RequestBody JSONObject parm, HttpServletRequest req){
            System.out.println("headerApi====="+parm.toJSONString());
            Enumeration<String> headers = req.getHeaderNames();
            JSONObject result = new JSONObject();
            while(headers.hasMoreElements()){
                String name = headers.nextElement();
                System.out.println("["+name+"]="+req.getHeader(name));
                result.put(name, req.getHeader(name));
            }
            result.put("descp", "this is from header");
            return result;
        }
    
        @RequestMapping("/header")
        public Object postWithHeader(){
        //该方法通过restTemplate请求远程restfulAPI
            HttpHeaders headers = new HttpHeaders();
            headers.set("auth_token", "asdfgh");
            headers.set("Other-Header", "othervalue");
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            JSONObject parm = new JSONObject();
            parm.put("parm", "1234");
            HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers);
            HttpEntity<String> response = restTemplate.exchange(
                    "http://localhost:8080/headerApi", HttpMethod.POST, entity, String.class);//这里放JSONObject, String 都可以。因为JSONObject返回的时候其实也就是string
            return response.getBody();
        }
    View Code
  • 相关阅读:
    Codeforces Round #513解题报告(A~E)By cellur925
    Luogu P1463 [POI2002][HAOI2007]反素数【数论/dfs】By cellur925
    NOIp2016 蚯蚓 【二叉堆/答案单调性】By cellur925
    Luogu P4139 上帝与集合的正确用法【扩展欧拉定理】By cellur925
    hdu 4704 Sum【组合数学/费马小定理/大数取模】By cellur925
    poj 1723 Soldiers【中位数】By cellur925
    MyBatis 简介
    对象导航查询和OID查询(补)
    Hibernate查询方式(补)
    Hibernate一级缓存(补)
  • 原文地址:https://www.cnblogs.com/lshan/p/10375232.html
Copyright © 2011-2022 走看看