posts - 93,  comments - 2,  trackbacks - 0
package com.zhihe.xqsh.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import com.zhihe.xqsh.network.ServerErrorException;

import android.accounts.NetworkErrorException;
import android.annotation.SuppressLint;
import android.util.Log;


public class CustomerHttpClient {
private static final String TAG = CustomerHttpClient.class.getSimpleName();

private static DefaultHttpClient customerHttpClient;

private CustomerHttpClient() {
}

public static synchronized HttpClient getHttpClient() {
if (null == customerHttpClient) {
HttpParams params = new BasicHttpParams();
// 设置�?��基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超时设置
/* 从连接池中取连接的超时时�?*/
ConnManagerParams.setTimeout(params, 2000);
ConnManagerParams.setMaxTotalConnections(params, 800);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 5000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 10000);

// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
// �?��连接数:ConnManagerParams.setMaxTotalConnections(params, 50);
customerHttpClient = new DefaultHttpClient(conMgr, params);
}
return customerHttpClient;
}

/**
* 以get方式提交数据
* @param url 提交地址
* @param params 参数
* @return 响应结果
* @throws ServerErrorException 请求失败
* @throws NetworkErrorException 连接失败
*/
public static String get(String url, String params) throws ServerErrorException, NetworkErrorException {
int tryTimes = 0;
NullPointerException ex;
do {
try {
return tryGet(url, params);
} catch (NullPointerException e) {
ex = e;
tryTimes++;
}
} while (tryTimes < 3);
throw ex;
}

/**
* 以get方式提交数据
* @param url 提交地址
* @param params 参数
* @return 响应结果
* @throws ServerErrorException 请求失败
* @throws NetworkErrorException 连接失败
*/
public static String tryGet(String url, String params) throws ServerErrorException, NetworkErrorException {
try {
HttpGet request = new HttpGet(url + params);

/*if (LotteryApplication.isCmwap()) {
org.apache.http.HttpHost proxy = new org.apache.http.HttpHost("10.0.0.172", 80, "http");
HttpParams httpParams = new BasicHttpParams();
ConnRouteParams.setDefaultProxy(httpParams, proxy);
request.setParams(httpParams);
}*/

HttpClient client = getHttpClient();
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new ServerErrorException("��������æ�����Ժ�����");
}
HttpEntity resEntity = response.getEntity();
String result = (resEntity == null) ? null : EntityUtils.toString(resEntity, "UTF-8");
return result;
} catch (UnsupportedEncodingException e) {
logw(e.getMessage());
return null;
} catch (ClientProtocolException e) {
logw(e.getMessage());
return null;
} catch (IOException e) {
throw new NetworkErrorException("���Ӳ��ɹ���������������", e);
}
}

private static void logw(String string) {
if (string != null) {
Log.w(TAG, string);
}
}

/**
* 以post方式提交数据
* @param url 提交地址
* @param params 参数
* @return 响应结果
* @throws ServerErrorException 请求失败
* @throws NetworkErrorException 连接失败
*/
public static String post(String url, List<NameValuePair> params) throws ServerErrorException, NetworkErrorException {
return post(url, params, null);
}

/**
* 以post方式提交数据
* @param url 提交地址
* @param params 参数
* @param soTimeout 响应超时时间,单位毫�?
* @return 响应结果
* @throws ServerErrorException 请求失败
* @throws NetworkErrorException 连接失败
*/
public static String post(String url, List<NameValuePair> params, int soTimeout) throws ServerErrorException,
NetworkErrorException {
HttpParams httpParams;
if (soTimeout <= 0) {
httpParams = null;
} else {
httpParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParams, soTimeout);
}
return post(url, params, httpParams);
}

/**
* 以post方式提交数据
* @param url 提交地址
* @param params 参数
* @param httpParams http参数
* @return 响应结果
* @throws ServerErrorException 请求失败
* @throws NetworkErrorException 连接失败
*/
public static String post(String url, List<NameValuePair> params, HttpParams httpParams) throws ServerErrorException,
NetworkErrorException {
int tryTimes = 0;
NullPointerException ex;
do {
try {
return tryPost(url, params, httpParams);
} catch (NullPointerException e) {
ex = e;
tryTimes++;
}
} while (tryTimes < 3);
throw ex;
}

/**
* 以post方式提交数据
* @param url 提交地址
* @param params 参数
* @param httpParams http参数
* @return 响应结果
* @throws ServerErrorException 请求失败
* @throws NetworkErrorException 连接失败
*/
public static String tryPost(String url, List<NameValuePair> params, HttpParams httpParams) throws ServerErrorException,
NetworkErrorException {
try {
HttpPost request = new HttpPost(url);
if (params != null && params.size() > 0) {
request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
}

// if (LotteryApplication.isCmwap()) {
// org.apache.http.HttpHost proxy = new org.apache.http.HttpHost("10.0.0.172", 80, "http");
// if (httpParams == null)
// httpParams = new BasicHttpParams();
// ConnRouteParams.setDefaultProxy(httpParams, proxy);
// }

if (httpParams != null)
request.setParams(httpParams);
//Log.v("CS", params.toString());
HttpClient client = getHttpClient();
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
//Log.v("CS", params.toString());
//Log.v("CS", response.getStatusLine().getStatusCode() + "");
request.abort(); 
throw new ServerErrorException("��������æ�����Ժ�����");
}
if (response.getStatusLine ().getStatusCode () != 200) {  
request.abort();  //�ж�����,���������Կ�ʼ��һ������
                return null;  
            } 
HttpEntity resEntity = response.getEntity();
String result = (resEntity == null) ? null : EntityUtils.toString(resEntity, "UTF-8");
//Log.v("CS", params.toString() + "||||" + result);
return result;
} catch (UnsupportedEncodingException e) {
logw(e.getMessage());
return null;
} catch (ClientProtocolException e) {
logw(e.getMessage());
return null;
} catch (IOException e) {
throw new NetworkErrorException(e.getMessage(), e);
//throw new NetworkErrorException("连接不成功,请检查网络设�?, e);
}
}

@SuppressLint("SdCardPath")
public static String download(String url) throws ServerErrorException, NetworkErrorException {
try {
//Log.i("http-download", url);
HttpPost request = new HttpPost(url);
HttpClient client = getHttpClient();
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new ServerErrorException("��������æ�����Ժ�����");
}

HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
if (is == null)
throw new ServerErrorException("stream is null ");

String fileExt = url.substring(url.lastIndexOf(".") + 1, url.length()).toLowerCase();
String fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));

File tempFile = new File("/sdcard/" + fileName + "." + fileExt);
if (!tempFile.exists())
tempFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);

byte[] buf = new byte[1024];
int ch;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
}

fileOutputStream.flush();
fileOutputStream.close();
return tempFile.getAbsolutePath();
} catch (UnsupportedEncodingException e) {
logw(e.getMessage());
return null;
} catch (ClientProtocolException e) {
logw(e.getMessage());
return null;
} catch (IOException e) {
throw new NetworkErrorException(e.getMessage(), e);
}
}

/**
* 清空cookie
*/
public static void clearCookie() {
if (customerHttpClient != null)
customerHttpClient.getCookieStore().clear();
}

/**
* 清除指定cookie
* @param name cookie名称
*/
public static void clearCookie(String name) {
if (customerHttpClient == null)
return;

BasicClientCookie expiredCookie = new BasicClientCookie(name, "null");
expiredCookie.setExpiryDate(new Date(System.currentTimeMillis() - 1000));
customerHttpClient.getCookieStore().addCookie(expiredCookie);
}
}
posted on 2015-07-13 22:10 Terry Zou 阅读(124) 评论(0)  编辑  收藏 所属分类: Android

只有注册用户登录后才能发表评论。


网站导航:
 
<2015年7月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

常用链接

留言簿(2)

随笔分类

随笔档案

文章分类

文章档案

相册

收藏夹

Java

搜索

  •  

最新随笔

最新评论

阅读排行榜

评论排行榜