package com.sino.publicclass.common;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HttpClientDownload {

	private ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
	private MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
	private boolean stop = false;

	protected final Log log = LogFactory.getLog(HttpClientDownload.class);

	private String fileUrl = "http://umsa.careland.com.cn/tmc/get_zone_traffic_snapshoot.ums?cdid=30000&cpid=12&kcard=108001100000002007697598&devidcode=22844C70CCTJ1&actcode=7142549098995416&verid=4C707502252C&zlibcomp=1";

	private int buffer = 1024 * 10;

	private String fileName = "TSPService.txt";

	public boolean isStop() {
		return stop;
	}

	public void setStop(boolean stop) {
		this.stop = stop;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFileUrl() {
		return fileUrl;
	}

	public void setFileUrl(String fileUrl) {
		this.fileUrl = fileUrl;
	}

	public int getBuffer() {
		return buffer;
	}

	public void setBuffer(int buffer) {
		this.buffer = buffer;
	}

	public byte[] getData() {
		return dataStream.toByteArray();
	}

	public ByteArrayOutputStream getDataStream() {
		return dataStream;
	}

	public void setDataStream(ByteArrayOutputStream dataStream) {
		this.dataStream = dataStream;
	}

	public boolean download() {
		HttpClient client = null;
		GetMethod httpGet = null;
		try {
			manager.getParams().setConnectionTimeout(100000);
			manager.getParams().setSoTimeout(100000);
			client = new HttpClient(manager);
			httpGet = new GetMethod(fileUrl);
			client.executeMethod(httpGet);
			String path = httpGet.getPath();

			int offset = path.lastIndexOf("/");
			if (offset != -1) {
				fileName = path.substring(offset + 1);
			} else {
				fileName = path;
			}
			if (fileName.indexOf(".") == -1) {
				fileName = fileName + ".htm";
			}
			if (fileName.equals(".htm")) {
				fileName = "123.htm";
			}
			InputStream in = httpGet.getResponseBodyAsStream();

			byte[] b = new byte[buffer];
			int len = 0;
			while ((len = in.read(b)) != -1 && !isStop()) {
				dataStream.write(b, 0, len);
			}
			in.close();

		} catch (Exception e) {
			log.error(e);
			return false;
		} finally {
			try {

				httpGet.releaseConnection();

			} catch (Exception e) {
				log.error(2);
				
			}
		}
		return true;
	}

	public static void main(String args[]) throws Exception {
		HttpClientDownload d = new HttpClientDownload();
		d.setFileUrl("http://api.map.baidu.com/?qt=cur&ie=utf-8&oue=3&res=json&wd=%E4%B8%8A%E6%B5%B7%E5%B8%82");
		if (d.download()) {

			System.out.println(1);
		}
	}
}
