package com.tykj.workflowcore.base.util;

import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;

import java.io.IOException;
import java.io.InputStream;

public class ResponseEntityUtil {

    public static String entityToString(CloseableHttpResponse response,String encode) {
        EntityThread entityThread = new EntityThread(response,encode);
        entityThread.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String result = null;
        result = entityThread.result;
        if (result == null) {
            entityThread.interrupt();
        }
        return result;
    }

    static class EntityThread extends Thread{

        CloseableHttpResponse response;
        String encode;
        String result;

        EntityThread( CloseableHttpResponse response,String encode){
            this.response = response;
            this.encode = encode;
        }
        @Override
        public void run() {
            try {
                InputStream responseStream = response.getEntity().getContent();
                result = IOUtils.toString(responseStream,encode);
                responseStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            super.run();
        }

    }
}
