首页 > 其他 > 详细

resttemplate post方法

时间:2017-10-23 12:30:52      阅读:739      评论:0      收藏:0      [点我收藏+]
@Component
@Slf4j
public class StatisticsService {
    private final RestTemplate restTemplate;
    private final ExamRepository repository;
    private final ExamService examService;

    @Autowired
    public StatisticsService(RestTemplate restTemplate, ExamRepository repository, ExamService examService) {
        this.restTemplate = restTemplate;
        this.repository = repository;
        this.examService = examService;
    }
  //上传功能实现
  public void postStatistics() throws Exception {
        int number = getLastedNumber();
        List<Integer> ids = repository.findAll().stream().filter(exam -> exam.getId().compareTo(number) > 0).map(Exam::getId).collect(Collectors.toList());
        post(Utils.getURI(Utils.URL.URL_POST_STATISTICS, getHeaders()), ids);
    }
  //封装的通用上传方法
  public void post(URI url, List<Integer> ids) throws Exception {
        ParameterizedTypeReference<ResponseBase<String>> ptr = new ParameterizedTypeReference<ResponseBase<String>>() {
        };
        //解压gzip
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build());
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
        for (Integer id : ids) {
            ExamService.ExamDetailResult data = examService.getExamDetailResult(id);
            String requestJson = new ObjectMapper().writeValueAsString(data);
            JSONObject obj = new JSONObject();
            obj.put("number", id);
            obj.put("data", requestJson);
            obj.put("type", 1);
            obj.put("version", "1.0.0");
            HttpEntity<String> requestEntity = new HttpEntity<>(obj.toString(), getHeaders());
            ResponseEntity<ResponseBase<String>> result = restTemplate.exchange(url, HttpMethod.POST, requestEntity, ptr);
            if (null == result.getBody().getData()) {
                throw new IllegalArgumentException("wrong action");
            }
        }
    }
  //设置头信息
  public MultiValueMap<String, String> getHeaders() {
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Accept", "application/json;charset=UTF-8");
        headers.set("Content-Type", "application/json;charset=UTF-8");
        headers.add("Authorization", "Basic YWRtaW46YWRxxxx=");
        return headers;
    }
}

 

resttemplate post方法

原文:http://www.cnblogs.com/xiaozhangqq1/p/7714819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!