在android与http服务器交互的方式主要是用httpClient类以及httppost、httpresponse结合的方式进行。
这里记录一个android客户端和http服务器交互的框架,框架的核心在于:
1、封装http请求信息,用ReqBean封装。
2、封装服务器返回数据信息,用httpres类封装。
3、客户端与服务器交互的耗时操作另开线程处理,并用回调机制获得服务器返回的数据。
4、用队列管理客户端的请求,加入线程锁。
代码贴出如下:
这是回调接口,onsuccess方法在服务器成功返回数据时执行,onerror在服务器返回数据失败时执行。
public interface OnLoadListener {
public void onSuccess(Object obj, ReqBean reqMode);
public void onError(Object obj, ReqBean bean);
}
Reqbean封装客户端请求信息,代码如下:
public class ReqBean implements Parcelable {
// 当前的上下文
private Context mContext = null;
// 下载地址
private String url = "";
// 请求类型,post或者get方式
private String reqType = "";
// 请求来源
private int reqMode = 0;
// 地址附带信息
private String json = "";
private Object obj = null;
private int index = -1;
private String newsId = "";
private OnLoadListener lister = null;//回调接口作为reqBean的成员变量
private String sourceUrl = "";
private Object mSyncToken = null;
public Object getmSyncToken() {
return mSyncToken;
}
public void setmSyncToken(Object mSyncToken) {
this.mSyncToken = mSyncToken;
}
public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getNewsId() {
return newsId;
}
public void setNewsId(String newsId) {
this.newsId = newsId;
}
public OnLoadListener getLister() {
return lister;
}
public void setLister(OnLoadListener lister) {
this.lister = lister;
}
public Context getContext() {
return mContext;
}
public void setContext(Context mContext) {
this.mContext = mContext;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getReqType() {
return reqType;
}
public void setReqType(String reqType) {
this.reqType = reqType;
}
public int getReqMode() {
return reqMode;
}
public void setReqMode(int reqMode) {
this.reqMode = reqMode;
}
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
@Override
public String toString() {
return " url : " + url + " reqType : " + reqType + " json: " + json;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
public void setObj(Object obj) {
this.obj = obj;
}
public Object getObj() {
return obj;
}
@Override
public boolean equals(Object obj) {
if (obj.getClass().getName().equals(this.getClass().getName())) {
if (obj instanceof ReqBean) {
ReqBean temp = (ReqBean) obj;
if (temp.getUrl().equalsIgnoreCase(this.getUrl()) && temp.getReqMode() == this.getReqMode()
&& temp.getJson().equals(this.getJson())) {
return true;
}
}
}
return false;
}
@Override
public int hashCode() {
return super.hashCode();
}
}
那么reqBean怎么被客户端发送到http服务器呢:
public static void sendRequest(ReqBean bean) {
if (loadHelper == null) {
loadHelper = LoadHelper.getInstance();
}
bean.setReqType("post");
loadHelper.addRequest(bean);
}
这里要说一说loadhelper类,这个类主要职责就是将reqBean塞到一个队列里,并保证线程安全,是这个框架的核心类:
public class LoadHelper {
private static final String TAG = LoadHelper.class.getSimpleName();
private static LoadHelper loadHelper = null;//单例模式实例
private boolean isRun = true;//是否运行的标志位
private volatile static int runCount = 0;//运行计数位
private static volatile int CONNECTCOUNT = 2;//连接计数
private Queue<ReqBean> mUnRunQueue = new LinkedList<ReqBean>();//等待队列
private Lock mUnRunQueueLock = new ReentrantLock();//访问控制锁
private Condition mUnRunQueueCondition = mUnRunQueueLock.newCondition();
private Object syncToken = new Object();//同步令牌
private LoadHelper() {
stopNet();
startNet();
initExceReq();
}
public synchronized void addRequest(ReqBean bean) {
if (null == bean) {
return;
}
put_unrun_Bean(bean);
}
public boolean put_unrun_Bean(ReqBean bean) {
mUnRunQueueLock.lock();
try {
if (mUnRunQueue.contains(bean)) {
return false;
}
if (!mUnRunQueue.offer(bean)) {
Log.e(TAG, "UnRun Queue is Full!");
return false;
} else {
mUnRunQueueCondition.signalAll();
Log.e(TAG, "put bean to UnRun Queue success![" + mUnRunQueue.size() + "]");
return true;
}
} finally {
mUnRunQueueLock.unlock();
}
}
public ReqBean get_unrun_Bean() {
mUnRunQueueLock.lock();
try {
if (mUnRunQueue.isEmpty()) {
mUnRunQueueCondition.await();
}
Log.v(TAG, "initExceReq 5");
return mUnRunQueue.poll();
} catch (InterruptedException e) {
e.printStackTrace();
Log.e(TAG, "gut_unrun_Bean mUnRunQueueCondition await Exception [" + e.toString() + "].");
return null;
} finally {
mUnRunQueueLock.unlock();
}
}
private void allowNextReq() {
synchronized (syncToken) {
if (runCount > 0) {
runCount -= 1;
LogUtils.v(TAG, "allowNextReq and runCount is " + runCount);
}
}
}
public synchronized void startNet() {
isRun = true;
}
public void stopNet() {
isRun = false;
mUnRunQueueLock.lock();
try {
mUnRunQueue.clear();
} finally {
mUnRunQueueLock.unlock();
}
}
public boolean getIsRun() {
return isRun;
}
public synchronized static LoadHelper getInstance() {
if (loadHelper == null) {
loadHelper = new LoadHelper();
}
return loadHelper;
}
private void initExceReq() {
Log.v(TAG, "initExceReq 1");
new Thread(new Runnable() {
@Override
public void run() {
while (isRun) {
// in one time max CONNECTCOUNT's mession run
boolean exceed_max_run_count = false;
synchronized (syncToken) {
exceed_max_run_count = (runCount >= CONNECTCOUNT);
LogUtils.v(TAG, "initExceReq 2 and exceed_max_run_count is : " + exceed_max_run_count);
}
if (exceed_max_run_count) {
LogUtils.v(TAG, "initExceReq 3 and exceed_max_run_count is and sleep");
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
e.printStackTrace();
Log.e(TAG, e.toString());
}
continue;
}
// get one not run bean
ReqBean bean = get_unrun_Bean();
if (null != bean) {
synchronized (syncToken) {
runCount += 1;
LogUtils.v(TAG, "initExceReq 4 and get_unrun_Bean() and runCount is " + runCount);
LogUtils.v(TAG, "initExceReq 6");
}
if (bean.getContext() != null) {
String netType = NetworkManager.getNetWorkType((ConnectivityManager) bean.getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE));
if (CommonConstants.WIFI_STATE.equalsIgnoreCase(netType)) {
CONNECTCOUNT = 8;
}
}
LogUtils.v(TAG, "initExceReq 7");
// put the bean to running queue and start a thread run it
// put_running_Bean(bean);
excePostReq(bean);
}
}
}
}).start();
}
private void excePostReq(final ReqBean bean) {
Log.v(TAG, "initExceReq 8");
Log.d(TAG, "exceReq in and bean is null ?---" + (null == bean));
new Thread(new Runnable() {
@Override
public void run() {
Log.v(TAG, "initExceReq 9");
HttpRes res = null;
if (bean != null) {
Log.v(TAG, "initExceReq 10");
if (Utility.isNotNull(bean.getUrl()) && bean.getReqType().equalsIgnoreCase("post")) {
Log.v(TAG, "initExceReq 11 bean.getUrl() = " + bean.getUrl());
res = HttpClientUtil.proxyHttpPost(bean.getContext(), bean.getUrl(), bean.getJson());
if (res != null) {
Log.d(TAG, "exceReq notifySuccessComm res != null ---" + bean.getUrl());
notifySuccessComm(res, bean);
} else {
Log.d(TAG, "exceReq notifyErrorComm res == null bean.getJson() ---" + bean.getJson());
Log.d(TAG, "exceReq notifyErrorComm res == null ---" + bean.getUrl());
notifyErrorComm(res, bean);
}
}
}
LogUtils.v(TAG, "one request is over and runcount is " + runCount);
allowNextReq();
}
}).start();
}
private void notifySuccessComm(final HttpRes entity, final ReqBean bean) {
final OnLoadListener listener = bean.getLister();
Log.w(TAG, " notifySuccessComm ----->" + listener);
if (entity != null) {
if (listener != null) {
listener.onSuccess(entity, bean);
}
} else {
notifyErrorComm(null, bean);
}
}
public void notifyErrorComm(final Object obj, final ReqBean bean) {
final OnLoadListener listener = bean.getLister();
{
if (listener != null) {
listener.onError(obj, bean);
Utility.freeReqBean(bean);
}
}
}
}
httpClientUtil是真正通过httpPost类将数据post到http服务器并且从服务器获得数据封装成httpRes的类:
private static HttpClient httpClient = null;
private static HttpClient userBindingClient = null;
// 解决javax.net.ssl.SSLPeerUnverifiedException no peer certificate
public static HttpClient getNewHttpClient(Context context) {
try {
if (httpClient == null) {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "gbk");
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
HttpConnectionParams.setSoTimeout(params, TIMEOUT);
ConnManagerParams.setTimeout(params, TIMEOUT);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
httpClient = new DefaultHttpClient(ccm, params);
}
httpClient = setNetWork(context, httpClient);
} catch (Exception e) {
}
return httpClient;
}
public static String get(Context context, String url, String encoding)
throws Exception {
String result = "";
HttpGet httpGet = null;
try {
httpGet = new HttpGet(url);
httpClient = getNewHttpClient(context);
HttpResponse res = httpClient.execute(httpGet);
result = getContent(res, encoding);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpGet != null) {
httpGet.abort();
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
}
return result;
}
public static String get(Context context, String url, String encoding,
DefaultHttpClient client) throws Exception {
String result = "";
HttpGet httpGet = null;
try {
httpClient = getNewHttpClient(context);
httpGet = new HttpGet(url);
HttpResponse res = client.execute(httpGet);
result = getContent(res, encoding);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpGet != null) {
httpGet.abort();
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
}
return result;
}
public static String post(Context context, String url, StringEntity se,
String host, String referer, String encoding) throws Exception {
String result = "";
HttpPost httpPost = null;
try {
httpClient = getNewHttpClient(context);
httpPost = new HttpPost(url);
httpPost.setEntity(se);
httpPost.setHeader("Host", host);
httpPost.setHeader("Referer", referer);
httpPost.setHeader("Accept", "*/*");
httpPost.setHeader("Accept-Language", "zh-cn");
httpPost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
httpPost.setHeader("UA-CPU", "x86");
httpPost.setHeader(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; InfoPath.2; CIBA)");
httpPost.setHeader("Connection", "close");
HttpResponse response = httpClient.execute(httpPost);
result = getContent(response, encoding);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpPost != null) {
httpPost.abort();
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
}
return result;
}
public static String httpPost(Context context, String url,
String queryString, String encoding) throws Exception {
String result = "";
HttpPost httpPost = null;
try {
httpClient = getNewHttpClient(context);
httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(queryString));
httpPost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
httpPost.getParams().setParameter("http.socket.timeout",
new Integer(20000));
httpPost.setHeader("Connection", "close");
HttpResponse response = httpClient.execute(httpPost);
result = getContent(response, encoding);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpPost != null) {
httpPost.abort();
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
}
return result;
}
public static String getContent(HttpResponse res, String encoding)
throws Exception {
HttpEntity ent = res.getEntity();
String result = IOUtils.toString(ent.getContent(), encoding);
ent.consumeContent();
return result;
}
public static HttpRes proxyHttpPost(Context context, String url, String json) {
String logHeader = "url : " + url + " json : " + json;
HttpPost httpPost = null;
HttpResponse response = null;
httpClient = getNewHttpClient(context);
HttpRes res = null;
try {
httpPost = new HttpPost(url);
httpPost.addHeader("Accept", "application/json, */*; q=0.01");
httpPost.addHeader("Accept-Encoding", "gzip,deflate");
httpPost = addParams(httpPost, json);
long startTime = System.currentTimeMillis();
LogUtils.v(TAG, "proxyHttpPost" + " start ---->" + startTime);
response = httpClient.execute(httpPost);
long endTime = System.currentTimeMillis();
LogUtils.v(TAG, logHeader + " end---->" + endTime + "use time :"
+ ((endTime - startTime) / 1000)
+ " proxyHttpPost response------->" + response);
if (response != null) {
StatusLine line = response.getStatusLine();
LogUtils.v(TAG, "proxyHttpPost" + " proxyHttpPost StatusLine------->"
+ line);
if (line != null) {
int resCode = line.getStatusCode();
LogUtils.v(TAG, "proxyHttpPost" + "proxyHttpPost resCode -- >"
+ resCode);
if (resCode == HttpStatus.SC_OK) {
res = new HttpRes();
res.setEntity(response.getEntity());
res.setHttpPost(httpPost);
}
}
}
} catch (Exception e) {
LogUtils.v(TAG, "proxyHttpPost" + "Exception resCode -- >"
+ e.toString());
e.printStackTrace();
res = null;
} finally {
LogUtils.v(TAG, "proxyHttpPost finally");
if (null == res && httpPost != null) {
LogUtils.v(TAG, "proxyHttpPost finally httpPost.abort();");
httpPost.abort();
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
}
return res;
}
public static HttpRes proxyHttpPost(Context context, String url, String json, String command) {
String logHeader = "url : " + url + " json : " + json;
HttpPost httpPost = null;
HttpResponse response = null;
httpClient = getNewHttpClient(context);
HttpRes res = null;
try {
httpPost = new HttpPost(url);
httpPost.addHeader("Secretflag", "false");
httpPost.addHeader("Accept-Encoding", "gzip");
httpPost.addHeader("Connection", "keep-alive");
httpPost.addHeader("User-Agent", "GAEA-Client");
httpPost.addHeader("Host", NormalRequestPiecer.PROPERTY_IP);
httpPost.addHeader("cmd", command);
httpPost.setEntity(new ByteArrayEntity(json.getBytes()));
LogUtils.v(TAG, logHeader + " proxyHttpPost httpPost----->" + httpPost);
LogUtils.v(TAG, logHeader + "httpClient----->" + httpClient);
long startTime = System.currentTimeMillis();
LogUtils.v(TAG, logHeader + " start ---->" + startTime);
response = httpClient.execute(httpPost);
long endTime = System.currentTimeMillis();
LogUtils.v(TAG, logHeader + " end---->" + endTime + "use time :" + ((endTime - startTime) / 1000)
+ " proxyHttpPost response------->" + response);
if (response != null) {
StatusLine line = response.getStatusLine();
LogUtils.v(TAG, logHeader + " proxyHttpPost StatusLine------->" + line);
if (line != null) {
int resCode = line.getStatusCode();
LogUtils.v(TAG, logHeader + "proxyHttpPost resCode -- >" + resCode);
if (resCode == HttpStatus.SC_OK) {
res = new HttpRes();
res.setEntity(response.getEntity());
res.setHttpPost(httpPost);
}
}
}
} catch (Exception e) {
e.printStackTrace();
LogUtils.e(TAG, logHeader + " proxyHttpPost connect : " + url + " Exception " + e.getMessage());
res = null;
if (httpPost != null) {
httpPost.abort();
}
} finally {
if (res == null && httpPost != null) {
httpPost.abort();
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
}
return res;
}
public static HttpRes postUserbinding(Context context, String url,
String json) {
Log.i(TAG, "postUserbinding json " + json);
HttpPost httpPost = null;
HttpResponse response = null;
HttpRes res = null;
userBindingClient = getUserBindingClient(context);
try {
httpPost = new HttpPost(url);
httpPost.addHeader("Accept-Encoding", "gzip");
response = userBindingClient.execute(addParams(httpPost, json));
/*
* Log.w(TAG,
* "postUserbinding response.getStatusLine().getStatusCode() -- >" +
* response.getStatusLine().getStatusCode());
*/
if (response != null) {
StatusLine line = response.getStatusLine();
LogUtils.v(TAG, "postUserbinding StatusLine------->" + line);
if (line != null) {
int resCode = line.getStatusCode();
LogUtils.v(TAG, "postUserbinding resCode -- >" + resCode
+ "end response url--->" + url);
if (resCode == HttpStatus.SC_OK) {
res = new HttpRes();
res.setEntity(response.getEntity());
res.setHttpPost(httpPost);
}
}
}
} catch (NullPointerException e) {
if (httpPost != null) {
httpPost.abort();
}
} catch (Exception e) {
res = null;
if (httpPost != null) {
httpPost.abort();
}
} finally {
if (res == null && httpPost != null) {
httpPost.abort();
}
if (userBindingClient != null) {
userBindingClient.getConnectionManager()
.closeExpiredConnections();
}
}
return res;
}
private static HttpClient getUserBindingClient(Context context) {
try {
if (userBindingClient == null) {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpConnectionParams.setConnectionTimeout(params,
USER_BINDING_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, USER_BINDING_TIMEOUT);
// SchemeRegistry registry = new SchemeRegistry();
// Scheme scheme = new Scheme("http",
// PlainSocketFactory.getSocketFactory(), 80);
// registry.register(scheme);
// ClientConnectionManager ccm = new
// ThreadSafeClientConnManager(params, registry);
userBindingClient = new DefaultHttpClient(params);
}
userBindingClient = setNetWork(context, userBindingClient);
// modify by wangtao on 20120712 end
} catch (Exception e) {
}
return userBindingClient;
}
private static HttpClient setNetWork(Context context, HttpClient client) {
String netType = NetworkManager
.getNetWorkType((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE));
if (!CommonConstants.WIFI_STATE.equalsIgnoreCase(netType)) {
if (!Utility.isOPhone()) {
Map<String, Object> map = NetworkManager.getProxy();
if (map != null && !map.isEmpty()) {
if (android.os.Build.VERSION.SDK_INT <= 7) {
String proxyHost = (String) map
.get(NetworkManager.PROXY_HOST);
int proxyPort = (Integer) map
.get(NetworkManager.PROXY_PORT);
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
client.getParams().setParameter(
ConnRoutePNames.DEFAULT_PROXY, proxy);
}
} else {
// cmnet set proxy
client.getParams().setParameter(
ConnRoutePNames.DEFAULT_PROXY, null);
}
}
// modify by wangtao on 20120712 start
} else if (CommonConstants.WIFI_STATE.equalsIgnoreCase(netType)) {
client.getParams()
.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
}
return client;
}
private static HttpPost addParams(HttpPost httpPost, String json) {
UrlEncodedFormEntity urlEncode = null;
List<NameValuePair> params = null;
try {
LogUtils.v(TAG, "addParams httpPost------>" + httpPost);
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("jsonRequest", json));
LogUtils.v(TAG, "params size " + params.size());
urlEncode = new UrlEncodedFormEntity(params, "GBK");
httpPost.setEntity(urlEncode);
} catch (Exception e) {
} finally {
if (params != null) {
params.clear();
params = null;
}
if (urlEncode != null) {
urlEncode = null;
}
}
return httpPost;
}
// modify by qianch for 修改下载方法 start
public static boolean downloadZipFile(Context context, String url,
String zipPath, String json) throws Exception {
HttpPost httpPost = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
InputStream in = null;
FileOutputStream out = null;
File file = null;
try {
file = new File(zipPath);
httpClient = getNewHttpClient(context);
httpPost = new HttpPost(url);
httpResponse = httpClient.execute(addParams(httpPost, json));
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_OK) {
// 获取响应实体
entity = httpResponse.getEntity();
long contentlength = entity.getContentLength();
Log.d(TAG, "Zip contentlength:" + contentlength);
if (!(contentlength > 0)) {
Log.d(TAG, "Zip File is not exist");
return false;
}
in = entity.getContent();
out = new FileOutputStream(file);
byte[] bytes = new byte[4096];
int c;
Log.v(TAG, "server msb file:begin: \n");
while ((c = in.read(bytes)) != -1) {
String content = new String(bytes, 0, c);
Log.v(TAG, content);
out.write(bytes, 0, c);
}
out.flush();
// add by qianch for 流量统计 start
// FlowUtil.recordFlow(contentlength);
// add by qianch for 流量统计 end
if (contentlength == file.length()) {
return true;
} else {
if (null != file && file.exists()) {
file.delete();
}
}
LogUtils.v(TAG, "server msb end: \n");
}
return true;
} catch (Exception e) {
e.printStackTrace();
if (null != file && file.exists()) {
file.delete();
}
if (httpPost != null) {
httpPost.abort();
}
} finally {
if (null != out) {
out.close();
}
if (null != in) {
in.close();
}
if (entity != null) {
entity.consumeContent();
}
if (httpPost != null) {
httpPost.abort();
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
}
return false;
}
@SuppressWarnings("finally")
public static boolean downloadApkFile(String url, String json, int mode,
Context context, OnDownloadListener listener, int type, long size,
Handler mHandler) throws Exception {
LogUtils.v(TAG, "downloadApkFile... type = " + type);
LogUtils.v(TAG, "url = " + url);
LogUtils.v(TAG, "json = " + json);
boolean ret = true;
try {
if (type == 1) {
LogUtils.i(TAG, "apk file out put");
File downloadFile = FileUtil.getApkRandomAccessFile(context);
if (null != downloadFile) {
LogUtils.d(TAG, "downloadFile" + downloadFile);
ret = breakPointDownload(context,downloadFile, url, size,listener, mHandler);
} else {
ret = false;
}
} else {
LogUtils.i(TAG, "patch file out put");
}
} catch (Exception e) {
ret = false;
}
return ret;
}
public static boolean breakPointDownload(Context context, File file,
String url, long size, OnDownloadListener listener, Handler mHandler) {
boolean ret = true;
InputStream in = null;
RandomAccessFile raf = null;
HttpGet httpGet = null;
long len = 0;
httpClient = getNewHttpClient(context);
try {
if (file != null && url != null && url.length() > 0) {
LogUtils.d(TAG, "file path is " + file.getAbsolutePath() + "and file length is " + file.length());
raf = new RandomAccessFile(file, "rw");
len = raf.length();
String start = "bytes=" + len + "-";
httpGet = new HttpGet(url);
httpGet.setHeader("Range", start);
HttpResponse httpResponse = httpClient.execute(httpGet);
//因为设置了range的头,将会导致永远都会是206
if(file.length() == httpResponse.getEntity().getContentLength()){
return true;
}else{
int responseCode = httpResponse.getStatusLine().getStatusCode();
LogUtils.i(TAG, "breakPointDownload responseCode = " + responseCode + "and file length is " + len);
if (responseCode == HttpStatus.SC_OK|| responseCode == HttpStatus.SC_PARTIAL_CONTENT) {
if (len == 0
|| (len > 0 && responseCode == HttpStatus.SC_PARTIAL_CONTENT)) {
long totalSize = httpResponse.getEntity()
.getContentLength();
long downloadSize = len;
LogUtils.d(TAG, "totalSize is " + totalSize + "and downloadSize is " + downloadSize);
in = httpResponse.getEntity().getContent();
LogUtils.d(TAG, "in available is " + in.available());
raf.seek(len);
byte[] bytes = new byte[4096];
int c;
// 断点下载时总量会变为剩下的大小
if((totalSize * currentDownload) / 100.0 - len < 0){
totalSize = (len * 100) / currentDownload;
} else {
currentDownload = 0;
}
while ((c = in.read(bytes)) != -1) {
raf.write(bytes, 0, c);
downloadSize += c;
// 显示通知栏更新进度 0x7为HomeActivity消息
currentDownload = (int) (downloadSize * 100.0 / totalSize);
LogUtils.v("currentDownload",currentDownload+">>"+downloadSize+">>"+totalSize+">>");
if (currentDownload >= ImClientService.lastRate + 5) {
ImClientService.lastRate = currentDownload;
Message msg = mHandler
.obtainMessage(ImClientService.DOWNLOAD_SERVICE);
msg.arg1 = currentDownload;
mHandler.sendMessage(msg);
}
if (listener != null
&& !listener.onDownload(size, downloadSize)) {
ret = false;
break;
}
}
} else {
ret = false;
}
}
if(ImClientService.lastRate != 100){
Message msg = mHandler
.obtainMessage(ImClientService.DOWNLOAD_SERVICE);
msg.arg1 = 100;
mHandler.sendMessage(msg);
}
if (ret == false) {
httpResponse.getEntity().consumeContent();
}
}
}
} catch (Exception e) {
ret = false;
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (raf != null) {
raf.close();
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
if (httpGet != null) {
httpGet.abort();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
@SuppressWarnings("finally")
public static File downloadImageFile(Context context, String url, File file) {
HttpEntity entity = null;
InputStream conIn = null;
DataInputStream in = null;
OutputStream out = null;
httpClient = getNewHttpClient(context);
HttpGet httpGet = null;
long totalSize = 0;
try {
long startTime = System.currentTimeMillis();
LogUtils.v(TAG, url + " downImage start-----" + startTime);
httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
LogUtils.v(TAG, url + " downloadImageFile httpResponse --->"
+ httpResponse);
if (httpResponse != null) {
long endTime = System.currentTimeMillis();
LogUtils.v(TAG, url + " downImage end-----" + endTime
+ " use time :" + ((endTime - startTime) / 1000));
StatusLine line = httpResponse.getStatusLine();
LogUtils.v(TAG, url + " downloadImageFile line --->" + line);
if (line != null) {
int responseCode = line.getStatusCode();
if (responseCode == HttpStatus.SC_OK) {
entity = httpResponse.getEntity();
if (entity != null) {
conIn = entity.getContent();
totalSize = entity.getContentLength();
// modify by qianch on 20130227 start
// FlowUtil.recordFlow(entity.getContentLength());
// modify by qianch on 20130227 end
in = new DataInputStream(conIn);
out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int byteread = 0;
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread);
}
} else {
if (file != null) {
file.delete();
file = null;
}
}
} else {
LogUtils.v(
"downImage",
url
+ " downLoadImage Server return error, response code = "
+ responseCode);
if (file != null) {
file.delete();
file = null;
}
}
} else {
if (file != null) {
file.delete();
file = null;
}
LogUtils.v("downImage", url
+ " Server return error, StatusLine " + line);
}
} else {
if (file != null) {
file.delete();
file = null;
}
LogUtils.v("downImage", url
+ " Server return error, httpResponse " + httpResponse);
}
} catch (Exception e) {
if (file != null) {
file.delete();
file = null;
}
if (httpGet != null) {
httpGet.abort();
}
} finally {
if (file != null) {
if (file.length() != totalSize) {
file.delete();
}
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (conIn != null) {
conIn.close();
}
if (entity != null) {
entity.consumeContent();
}
if (httpGet != null) {
httpGet.abort();
httpGet = null;
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
@SuppressWarnings("finally")
public static File downloadFile(Context context, String url, String json,
File downloadfile, ReqFileBean bean) {
Log.i(TAG, "url:" + url + " filepath:" + downloadfile.getAbsolutePath()
+ " name:" + downloadfile.getName());
HttpEntity entity = null;
InputStream contentInstream = null;
DataInputStream in = null;
OutputStream out = null;
httpClient = getNewHttpClient(context);
// httpClient = new DefaultHttpClient();
// HttpPost httpPost = null;
HttpGet httpGet = null;
try {
// httpPost = new HttpPost(url);
httpGet = new HttpGet(url);
// HttpResponse httpResponse =
// httpClient.execute(addParams(httpPost, json));
HttpResponse httpResponse = httpClient.execute(httpGet);
int responseCode = httpResponse.getStatusLine().getStatusCode();
Log.i(TAG, "responseCode:" + responseCode);
if (responseCode == HttpStatus.SC_OK) {
entity = httpResponse.getEntity();
contentInstream = entity.getContent();
in = new DataInputStream(contentInstream);
out = new FileOutputStream(downloadfile);
byte[] buffer = new byte[256 * 1024];
int byteread = 0;
int lastpercent = 0;
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread);
bean.setCurrentLen(bean.getCurrentLen() + byteread);
int percent = (int) (100 * bean.getCurrentLen() / bean
.getFileLength());
if (percent != lastpercent)
{
bean.setPercent(percent);
// bean.getListener().onLoadPercent(bean);
// 发送广播更新进度条
Intent intent = new Intent();
intent.setAction(CommonConstants.ACTION_DOWNLOAD_PROGRESS);
Bundle bundle = new Bundle();
String chatId = bean.getChatId();
bundle.putString(CommonConstants.KEY_CHAT_ID, chatId);
bundle.putInt(CommonConstants.KEY_LOAD_PRECENT, percent);
intent.putExtras(bundle);
IMApplication.getAppContext().sendBroadcast(intent);
// 更新数据库进度
ChatDBManager.getInstance(IMApplication.getAppContext())
.updateDownUploadFileProgress(chatId, percent,
ChatMsgItem.DOWNLOADING);
lastpercent = percent;
}
}
out.flush();
Log.i(TAG, "flush");
} else {
LogUtils.v(TAG, "Server return error, response code = "
+ responseCode);
if (downloadfile != null) {
downloadfile.delete();
downloadfile = null;
}
}
} catch (Exception e) {
if (downloadfile != null) {
downloadfile.delete();
downloadfile = null;
}
if (httpGet != null) {
httpGet.abort();
}
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (contentInstream != null) {
contentInstream.close();
}
if (entity != null) {
entity.consumeContent();
}
if (httpGet != null) {
httpGet.abort();
}
if (httpClient != null) {
httpClient.getConnectionManager().closeExpiredConnections();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return downloadfile;
}
public static String getString(InputStream is) {
BufferedReader reader = null;
StringBuffer responseText = null;
String readerText = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "gb2312"));
responseText = new StringBuffer();
readerText = reader.readLine();
while(readerText != null){
responseText.append(readerText);
responseText.append(System.getProperty("line.separator"));
readerText = reader.readLine();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseText.toString();
}
private static void notifySuccessComm(final HttpRes entity, final ReqBean bean) {
final OnLoadListener listener = bean.getLister();
Log.w(TAG, " notifySuccessComm ----->" + listener);
if (entity != null) {
if (listener != null) {
listener.onSuccess(entity, bean);
}
} else {
notifyErrorComm(null, bean);
}
}
public static void notifyErrorComm(final Object obj, final ReqBean bean) {
final OnLoadListener listener = bean.getLister();
{
if (listener != null) {
listener.onError(obj, bean);
Utility.freeReqBean(bean);
}
}
}
}