1.main.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.text.TextUtils;
import android.widget.Toast;
public void getHttpInfo(){
final MyTask mMyTask = MyTask.newInstance();
try {
final ProgressDialog pd = new ProgressDialog(context);
pd.setTitle("title");
pd.setMessage(context.getText(messageResId));// 如果messageResId是定义在xml中
pd.setCancelable(false);
pd.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (mMyTask != null) {
mMyTask.doCancel();
}
}
});
pd.show();
mMyTask.doRequest(this,"http://testurl", new MyTaskListener() {
@Override
public void onCallback(String response) {
if(pd != null){
pd.dismiss();
}
if (TextUtils.isEmpty(response)) {
Toast.makeText(this,"获取信息失败",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this,response, Toast.LENGTH_LONG).show();
}
}
});
}catch(Exception e){
e.printStackTrace();
}
}
2.MyTask.java
import android.content.Context;
import android.util.Log;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class MyTask{
private MyHttpTask sHttpTask;
public static MyTask newInstance(){
return new MyTask();
}
public void doRequest(Context context,String url,final MyTaskListener listener){
if (sHttpTask != null) {
sHttpTask.cancel(true);
}
sHttpTask = new MyHttpTask(context);
MyHttpListener myHttpListener = new MyHttpListener() {
@Override
public void onResponse(String response) {
Log.d(TAG, "onResponse=" + response);
listener.onCallback(response);
sHttpTask = null;
}
@Override
public void onCancelled() {
Log.d(TAG, "onCancelled");
listener.onCallback(null);
sHttpTask = null;
}
};
// 以下四种方式选一
// 1.调用get(多任务)
sHttpTask.doGetOnExecutor(myHttpListener,url);
// 2.调用post(多任务)
ArrayList
params = new ArrayList();
//建立一个NameValuePair数组,用于存储欲传送的参数
params.add(new BasicNameValuePair("pwd","2544"));
params.add(new BasicNameValuePair("city", city));
sHttpTask.doPostOnExecutor(myHttpListener,params,url);
// 3.调用get(单任务)
sHttpTask.doGet(myHttpListener,url);
// 4.调用post(单任务)
sHttpTask.doPost(myHttpListener,params,url);
}
public boolean doCancel() {
return (sHttpTask != null) ? sHttpTask.cancel(true) : false;
}
}
3.MyTaskListener.java
public interface MyTaskListener {
public void onCallback(String response);
}
4.MyHttpTask.java
import android.os.AsyncTask;
import android.content.Context;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.http.HttpResponse;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.client.ClientProtocolException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.HttpEntity;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class MyHttpTask extends AsyncTask {
private static final int MAX_RETRY_TIME = 3;
private static final int CONN_TIMEOUT = 15000;
private static final int SO_TIMEOUT = 20000;
private MyHttpListener mListener;
private boolean mIsHttpPost;
private int mRetryCount;
private static ExecutorService mPools = Executors.newFixedThreadPool(3);
private ArrayList mKeyValueArray;
private Context mContext;
public MyHttpTask(Context context) {
mContext = context;
}
public void doGet(SdkHttpListener listener, String url) {
this.mListener = listener;
this.mIsHttpPost = false;
this.mRetryCount = 0;
execute(url);
}
public void doPost(SdkHttpListener listener,
ArrayList keyValueArray,
String url) {
this.mListener = listener;
this.mIsHttpPost = true;
this.mKeyValueArray = keyValueArray;
this.mRetryCount = 0;
execute(url);
}
public void doGetOnExecutor(MyHttpListener listener, String url) {
this.mListener = listener;
this.mIsHttpPost = false;
this.mRetryCount = 0;
if(mPools == null){
mPools = Executors.newFixedThreadPool(3);
}
executeOnExecutor(mPools,url);
}
public void doPostOnExecutor(SdkHttpListener listener,
ArrayList keyValueArray,
String url) {
this.mListener = listener;
this.mIsHttpPost = true;
this.mKeyValueArray = keyValueArray;
this.mRetryCount = 0;
executeOnExecutor(mPools, url);
}
@Override
protected String doInBackground(String... params) {
String response = null;
while (response == null && mRetryCount < MAX_RETRY_TIME) {
if (isCancelled())
return null;
try {
String uri = params[0];
HttpResponse httpResp = executeHttp(mContext, uri);
if (httpResp != null && !isCancelled()) {
int st = httpResp.getStatusLine().getStatusCode();
HttpEntity entity = httpResp.getEntity();
if (entity != null) {
InputStream content = entity.getContent();
if (content != null) {
response = convertStreamToString(content);
}
}
}
} catch (SSLHandshakeException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mRetryCount++;
}
return response;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (mListener != null && !isCancelled()) {
mListener.onResponse(response);
mListener = null;
}
}
@Override
protected void onCancelled() {
super.onCancelled();
if (mListener != null) {
mListener.onCancelled();
mListener = null;
}
}
private HttpResponse executeHttp(Context context,String uri) throws SSLHandshakeException,ClientProtocolException,IOException {
return mIsHttpPost ? post(context, uri, mKeyValueArray) : get(context, uri);
}
private static HttpResponse post(Context context, String url, ArrayList params)throws SSLHandshakeException, ClientProtocolException, IOException {
boolean isParam = params != null;
url = url.replaceAll(" ", "%20");
HttpClient httpClient = new DefaultHttpClient();
HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
HttpClientParams.setRedirecting(httpParams, false);
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setHeader("Charset", "UTF-8");
if (isParam) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
}
return httpClient.execute(post);
}
private static HttpResponse get(Context context, String url)throws SSLHandshakeException,ClientProtocolException,IOException {
url = url.replaceAll(" ", "%20");
HttpClient httpClient = new DefaultHttpClient();
HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
HttpClientParams.setRedirecting(httpParams, false);
HttpGet get = new HttpGet(url);
get.setHeader("Content-Type", "application/x-www-form-urlencoded");
get.setHeader("Charset", "UTF-8");
return httpClient.execute(get);
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
5.MyHttpListener.java
public interface MyHttpListener {
public void onResponse(String response);
public void onCancelled();
}