package com.zjrs.ggfw.yjt.util;


import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class RestRequestUtil {

    private final RestTemplate restTemplate;

    public RestRequestUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if(response.getRawStatusCode() != 401){
                    super.handleError(response);
                }
            }
        });
    }

    public <T> String request(String url, HttpEntity<T> entity) throws IOException {
        InputStream is =null;
        BufferedReader br=null;
        try {
            this.restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
            this.restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

            ResponseEntity<Resource> responseEntity =this.restTemplate.postForEntity(url,entity, Resource.class);
            is = responseEntity.getBody().getInputStream();
            br = new BufferedReader(new InputStreamReader(is,"GB2312"));
            String ret=null;
            StringBuilder sb = new StringBuilder();
            while ((ret = br.readLine()) != null){
                sb.append(ret);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                is.close();
            }
            if(br!=null){
                br.close();
            }
        }
        return null;
    }
}
