【spring】RestTemplate发送请求,请求第三方接口 的几种请求方式POST,GET,DELETE,PUSH...

org.springframework.web.client.RestTemplate

 参考地址:http://www.cnblogs.com/UniqueColor/p/7123347.html

GitHub源码地址:

使用示例代码:

public int doClear(List typeList, CodeChangeLog codeChangeLog) {
        AdminUser adminUser = AdminUser.createFeignUser("ms-code");
        List scList = codeChangeLog.getScList();
        
        HttpHeaders requestHeaders = new HttpHeaders();
        MediaType contentType = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(contentType);
        requestHeaders.add("x-admin-info", JSON.toJSONString(adminUser));
        CodeChangeReqBean reqBean = new CodeChangeReqBean();
        reqBean.setScList(scList);
        HttpEntity requestEntity = new HttpEntity(JSON.toJSONString(reqBean), requestHeaders);
        
        JSONObject jsonObj = new JSONObject();
        //失败个数
        int failNum = typeList.size();
        
        for (CodeChangeOption clearType : typeList) {
            String uid = clearType.getUid();
            int reqSuccess = CodeChangeLog.CHANGE_FAIL;
            //发送清除请求
            String url = "http://" + clearType.getAppName() + clearType.getApiPath();
            
            ResponseEntity response = null;
            try {
                response = lunaRestTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
                if (response != null && response.getStatusCode() == HttpStatus.OK) {
                    //请求成功
                    String body = response.getBody();
                    JSONObject parseObject = JSON.parseObject(body);
                    if (parseObject.getBoolean("success")) {
                        // type : success
                        failNum--;
                        reqSuccess = CodeChangeLog.CHANGE_SUCCESS;
                    }
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", clearType.getName());
            jsonObject.put("success", reqSuccess);
            jsonObj.put(uid, jsonObject);
            
        }
        codeChangeLog.setChangeJsonString(jsonObj.toJSONString());
        if(failNum == 0){
            codeChangeLog.setSuccess(CodeChangeLog.CHANGE_SUCCESS);
        }else{
            codeChangeLog.setSuccess(CodeChangeLog.CHANGE_FAIL);
        }
        //修改日志记录
        return mapper.update(codeChangeLog);
        
    }
View Code

 

你可能感兴趣的:(【spring】RestTemplate发送请求,请求第三方接口 的几种请求方式POST,GET,DELETE,PUSH...)