public class DataTools {
public static final String TAG = "HttpTools";
/**
* 连接超时时间,毫秒
*/
private static final int TIME_OUT = 20000;
/**
* 网络通信缓存
*/
private static final int HTTP_CACHE = 1024 * 100;
private Context mContext;
private boolean mFinish = false;
public DataTools(Context mContext) {
this.mContext = mContext;
}
/**
* 中断数据连接
*/
public void disConnection(){
mFinish = true;
}
/**
* 解压Gzip格式的字节流
* @param data Gzip格式字节流
* @return 解析后的字符
*/
public String decompressData(byte[] data) throws Exception{
return new String(decompress(data));
}
/**
* 上传文件
* @param urlPath 请求网址
* @param multipartData
* @return 服务端返回的信息
*/
public byte[] uploadMultipartData(String urlPath, MultipartEntity multipartData){
StringBuffer result = new StringBuffer("");
try{
byte[] cache = new byte[HTTP_CACHE];
// MultipartEntity mpEntity = new MultipartEntity();
//文本内容
// if (params != null && !params.isEmpty()) {
//
// for (Map.Entry<String, String> entry : params.entrySet()) {
//
//
//
// StringBody par = new StringBody(entry.getValue());
//
// mpEntity.addPart(entry.getKey(), par);
//
// }
//
// }
// 图片
// if(map != null){
// for(Map.Entry<String, String> entry : map.entrySet()){
//
// FileBody file = new FileBody(new File(entry.getValue()));
//
// mpEntity.addPart(entry.getKey(), file);
//
// }
// }
HttpPost hp = new HttpPost(urlPath);
hp.setEntity(multipartData);
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT); // 设置请求超时时间
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT); // 读取超时
client.getParams().setParameter(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
HttpResponse response = client.execute(hp);
final int code = response.getStatusLine().getStatusCode();
if(code == HttpStatus.SC_OK){
System.out.println("the web was responsed");
InputStream inStream = response.getEntity().getContent();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while((len = inStream.read(cache)) > 0) {
bos.write(cache, 0, len);
if(mFinish){
mFinish = false;
throw new RuntimeException("the program disconnection the connection");
}
}
bos.close();
return bos.toByteArray();
}else{
}
}catch (Exception e) {
Log.e(TAG, e.toString());
}finally{
}
return null;
}
/**
* 通过POST数据到指定的网址获取数据,指定网址必须返回GZIP格式的数据,该方法会将数据解析成可用字符串
* <br>该方法会使线程堵塞,建议单独开启一条线程执行该方法。
* <br>该方法适合返回字符串数据,如果数据量过大请考虑拆分数据,或者参考Java文件下载方式。
* GET the data from specified URL, this method will use Gzip format to parse the data.
* @param urlPath URL path
* @param withCache whether or not cache the data returned, if it is false, you can't get the data from cached pool,
* and you can't cached the data from URL.
* @return 将数据解压缩后变成字符串
*/
public String postZipData(String urlPath, Map<String, String> map, boolean withCache){
WebCacheManager wcm = new WebCacheManager(mContext);
StringBuffer result = new StringBuffer("");
StringBuffer newUrl = new StringBuffer("");
try{
if(withCache){
newUrl.append(urlPath);
if(map != null){
for(Map.Entry<String, String> entry : map.entrySet()){
newUrl.append("&" + entry.getKey() + "=" + entry.getValue());
}
}
byte[] data = wcm.getCache(newUrl.toString());
if(data != null){
return decompressData(data);
}
}
byte[] cache = new byte[HTTP_CACHE];
HttpPost hp = new HttpPost(urlPath);
List <NameValuePair> params=new ArrayList<NameValuePair>();
//assembled data
if(map != null){
for(Map.Entry<String, String> entry : map.entrySet()){
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
hp.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT); // 设置请求超时时间
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT); // 读取超时
client.getParams().setParameter(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
HttpResponse response = client.execute(hp);
final int code = response.getStatusLine().getStatusCode();
if(code == HttpStatus.SC_OK){
Log.i(TAG, "the http resposed");
InputStream inStream = response.getEntity().getContent();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while((len = inStream.read(cache)) > 0) {
bos.write(cache, 0, len);
if(mFinish){
mFinish = false;
throw new RuntimeException("the program interrupt the connection");
}
}
bos.close();
byte[] compressData = bos.toByteArray();
//加入缓存
if(withCache){
wcm.setCache(newUrl.toString(), compressData);
}
result.append(new String(decompress(compressData)));
inStream.close();
return result.toString();
}else{
}
}catch (Exception e) {
Log.e(TAG, e.toString());
}finally{
wcm.release();
}
return null;
}
/**
* 通过POST方式请求数据,
* <br>该方法会使线程堵塞,建议单独开启一条线程执行该方法。
* <br>该方法适合返回字符串数据,如果数据量过大请考虑拆分数据,或者参考Java文件下载方式。
* @param urlPath URL path
* @param withCache whether or not cache the data, if it is false, you can't get the data from cached pool,
* and you can't cached the data from URL.
* @return 将数据解压缩后变成字符串
*/
public String postData(String urlPath, Map<String, String> map, boolean withCache){
WebCacheManager wcm = new WebCacheManager(mContext);
StringBuffer result = new StringBuffer("");
StringBuffer newUrl = new StringBuffer("");
try{
if(withCache){
newUrl.append(urlPath);
if(map != null){
for(Map.Entry<String, String> entry : map.entrySet()){
newUrl.append("&" + entry.getKey() + "=" + entry.getValue());
}
}
byte[] data = wcm.getCache(newUrl.toString());
if(data != null){
return decompressData(data);
}
}
HttpPost hp = new HttpPost(urlPath);
List <NameValuePair> params=new ArrayList<NameValuePair>();
//assembled data
if(map != null){
for(Map.Entry<String, String> entry : map.entrySet()){
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
hp.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT); // 设置请求超时时间
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT); // 读取超时
client.getParams().setParameter(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
HttpResponse response = client.execute(hp);
final int code = response.getStatusLine().getStatusCode();
if(code == HttpStatus.SC_OK){
Log.i(TAG, "the http resposed");
InputStream inStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
while(true){
final String s = reader.readLine();
if(s != null){
result.append(s);
}else{
break;
}
if(mFinish){
mFinish = false;
throw new RuntimeException("the program disconnection the connection");
}
}
//加入缓存
if(withCache){
wcm.setCache(urlPath, compress(result.toString().getBytes()));
}
inStream.close();
return result.toString();
}else{
}
}catch (Exception e) {
Log.e(TAG, e.toString());
result = new StringBuffer("");
}finally{
wcm.release();
}
return null;
}
/**
* 通过指定的网址获取数据,指定网址必须返回GZIP格式的数据,该方法会将数据解析成可用字符串
* <br>该方法会使线程堵塞,建议单独开启一条线程执行该方法。
* <br>该方法适合返回字符串数据,如果数据量过大请考虑拆分数据,或者参考Java文件下载方式。
* GET the data from specified URL, this method will use Gzip format parse the data.
* @param urlPath URL path
* @param withCache whether or not cache the data returned, if it is false, you can't get the data from cached pool,
* and you can't cached the data from URL.
* @return 将数据解压缩后变成字符串
*/
public String getZipData(String urlPath, boolean withCache){
WebCacheManager wcm = new WebCacheManager(mContext);
StringBuffer result = new StringBuffer("");
try{
if(withCache){
byte[] data = wcm.getCache(urlPath);
if(data != null){
return decompressData(data);
}
}
URL url = new URL(urlPath);
byte[] cache = new byte[HTTP_CACHE];
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(TIME_OUT);
http.setReadTimeout(TIME_OUT);
http.setRequestMethod("GET");
http.setRequestProperty("Charset", HTTP.UTF_8);
http.setRequestProperty(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
http.connect();
final int code = http.getResponseCode();
if(code == HttpStatus.SC_OK){
Log.i(TAG, "the http resposed");
InputStream inStream = http.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while((len = inStream.read(cache)) > 0) {
bos.write(cache, 0, len);
if(mFinish){
mFinish = false;
throw new RuntimeException("the program disconnection the connection");
}
}
bos.close();
byte[] compressData = bos.toByteArray();
//加入缓存
if(withCache){
wcm.setCache(urlPath, compressData);
}
result.append(new String(decompress(compressData)));
inStream.close();
http.disconnect();
http = null;
return result.toString();
}else{
}
}catch (Exception e) {
Log.e(TAG, e.toString());
}finally{
wcm.release();
}
return null;
}
/**
* 通过指定的网址获取数据
* <br>该方法会使线程堵塞,建议单独开启一条线程执行该方法。
* <br>该方法适合返回字符串数据,如果数据量过大请考虑拆分数据,或者参考Java文件下载方式。
* @param urlPath URL path
* @param withCache whether or not cache the data returned, if it is false, you can't get the data from cached pool,
* and you can't cached the data from URL.
* @return 将数据解压缩后变成字符串
*/
public String getData(String urlPath, boolean withCache){
WebCacheManager wcm = new WebCacheManager(mContext);
StringBuffer result = new StringBuffer("");
try{
if(withCache){
byte[] data = wcm.getCache(urlPath);
if(data != null){
return decompressData(data);
}
}
URL url = new URL(urlPath);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(TIME_OUT);
http.setReadTimeout(TIME_OUT);
http.setRequestMethod("GET");
http.setRequestProperty("Charset", HTTP.UTF_8);
http.setRequestProperty(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
http.connect();
final int code = http.getResponseCode();
if(code == HttpStatus.SC_OK){
Log.i(TAG, "the http resposed");
InputStream inStream = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
while(true){
final String s = reader.readLine();
if(s != null){
result.append(s);
}else{
break;
}
if(mFinish){
mFinish = false;
throw new RuntimeException("the program disconnection the connection");
}
}
//加入缓存
if(withCache){
wcm.setCache(urlPath, compress(result.toString().getBytes()));
}
inStream.close();
http.disconnect();
http = null;
return result.toString();
}else{
}
}catch (Exception e) {
Log.e(TAG, e.toString());
}finally{
wcm.release();
}
return null;
}
/**
* 对字节流进行Gzip格式压缩
* @param bytes 源字节
* @return 压缩后的字节
* @throws IOException
* @throws DataFormatException
*/
public byte[] compress(byte[] bytes) throws IOException, DataFormatException{
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
compressor.setInput(bytes);
compressor.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
byte[] buf = new byte[HTTP_CACHE];
int len = 0;
while(!compressor.finished()){
len = compressor.deflate(buf);
bos.write(buf, 0, len);
}
bos.close();
return bos.toByteArray();
}
/**
* 对Gzip格式的字节进行解压
* @param bytes Gzip字节
* @return 解压后的字节
* @throws IOException
* @throws DataFormatException
*/
public byte[] decompress(byte[] bytes) throws IOException, DataFormatException{
// 创建解压缩器
Inflater decompressor = new Inflater();
decompressor.setInput(bytes);
// 解压缩后的数据写入内存数组中
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
final byte[] buffer = new byte[HTTP_CACHE];
while (!decompressor.finished()) {
len = decompressor.inflate(buffer);
bos.write(buffer, 0, len);
}
decompressor.end();
bos.close();
return bos.toByteArray();
}
}