resttemplate post方法上傳資源


@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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM