package com.imofan.android.basic.update;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

/**
 * 下载工具
 * @author user
 *
 */
public class MFHttpUtils {
    
    private final static String ACCEPT_ENCODING = "gzip, deflate";
    
    /**
     * 连接超时
     */  
    public static int CONNECT_TIMEOUT = 20;
    
    /**
     * socket超时
     */
    public static int DATA_TIMEOUT = 40;
    
    /**
     * 获取指定URL的文本内容
     * @param urlStr 要获取的文本文件的URL
     * @return 文本文件的内容
     * @throws IOException
     */
    public static String invokeText(String urlStr) throws IOException {
        StringBuffer textBuff = new StringBuffer();
        HttpGet request = new HttpGet(urlStr);
        request.addHeader("Accept-Encoding", ACCEPT_ENCODING);

        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT *1000);
        HttpConnectionParams.setSoTimeout(params, DATA_TIMEOUT *1000);
        HttpClient httpClient = new DefaultHttpClient(params);

        String line;
        BufferedReader reader = null;
        try {
            HttpResponse response = httpClient.execute(request);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                InputStream is = response.getEntity().getContent();
                Header contentEncoding = response.getFirstHeader("Content-Encoding");
                if(contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    is = new GZIPInputStream(is);
                }
                reader = new BufferedReader(new InputStreamReader(is));
                while((line = reader.readLine()) != null) {
                    textBuff.append(line).append("\r\n");
                }
            }
        } finally {
            if(reader != null) {
                reader.close();
            }
        }
        return textBuff.toString();
    }
}
