首先封装一个基本的HTTP请求类:
package com.yxks.testrc2.utils;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import org.apache.http.params.HttpConnectionParams;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import static java.net.Proxy.Type.HTTP;
/**
* Created by Administrator on 2016/12/15.
*/
public class HttpConnectionUtils implements Runnable {
private static final String TAG = HttpConnectionUtils.class.getSimpleName();
public static final int DID_START = 0;
public static final int DID_ERROR = 1;
public static final int DID_SUCCEED = 2;
public static final int MSGTYPE_STRING = 0;
public static final int MSGTYPE_BITMAP = 1;
private static final int GET = 0;
private static final int POST = 1;
private static final int PUT = 2;
private static final int DELETE = 3;
private static final int BITMAP = 4;
private String url = "";
private int method;
private int timeout = 500;
private Handler handler;
Map, String> data;
private HttpURLConnection conn;
public HttpConnectionUtils() {
this(new Handler());
}
public HttpConnectionUtils(Handler _handler) {
handler = _handler;
}
public void create(int method, String url, Map data, int timeout) {
Log.d(TAG, "method:"+method+" ,url:"+url+" ,data:"+data);
this.method = method;
this.url = url;
this.data = data;
this.timeout = timeout;
ConnectionManager.getInstance().push(this);
}
public void get(String url, int timeout) {
create(GET, url, null, timeout);
}
public void post(String url, Map data, int timeout) {
create(POST, url, data, timeout);
}
public void put(String url, Map data, int timeout) {
create(PUT, url, data, timeout);
}
public void delete(String url, int timeout) {
create(DELETE, url, null, timeout);
}
public void bitmap(String url, int timeout) {
create(BITMAP, url, null, timeout);
}
private String prepareParam(){
StringBuffer sb = new StringBuffer();
if(null == data) {
return "";
}
if (data.size() <= 0){
return "";
} else {
for (String key : data.keySet()) {
if(sb.length() < 1) {
sb.append(key).append("=" ).append(data.get(key));
} else {
sb.append("&" ).append(key).append( "=" ).append(data.get(key));
}
}
return sb.toString();
}
}
@Override
public void run() {
try {
URL httpUrl = new URL(url); //创建URL对象
handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_START));
conn = (HttpURLConnection) httpUrl.openConnection();
conn.setConnectTimeout(this.timeout);//设置连接超时
switch(this.method) {
case GET: {
conn.setRequestMethod("GET");
break;
}
case POST: {
conn.setRequestMethod("POST");
conn.setDoInput(true );
conn.setDoOutput(true );
//填写参数
String paramStr = prepareParam();
OutputStream os = conn.getOutputStream();
os.write(paramStr.toString().getBytes("utf-8" ));
os.close();
break;
}
case DELETE:{
conn.setRequestMethod("DELETE");
break;
}
case BITMAP:{
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setUseCaches(true);//使用缓存
break;
}
}
conn.connect();
if (conn.getResponseCode() != conn.HTTP_OK) {
handler.sendMessage(Message.obtain(handler, DID_ERROR));
} else {
if(this.method != BITMAP) {//非图片获取
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line, result = "";
while ((line = br.readLine()) != null) {
result += line;
}
Log.i("LoginActivity", "**************response=" + result);
Message message = Message.obtain(handler, DID_SUCCEED, MSGTYPE_STRING, 0, result);
handler.sendMessage(message);
} else {
Bitmap bitmap=null;
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
Message message = Message.obtain(handler, DID_SUCCEED, MSGTYPE_BITMAP, 0, bitmap);
handler.sendMessage(message);
}
}
} catch (Exception e) {
e.printStackTrace();
handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_ERROR, e));
} finally {
if (conn != null) {
conn.disconnect(); //中断连接
}
}
ConnectionManager.getInstance().didComplete(this);
}
}
然后封装一个统一进行请求的类:
package com.yxks.testrc2.utils;
import java.util.ArrayList;
/**
* Created by Administrator on 2016/12/15.
*/
public class ConnectionManager {
public static final int MAX_CONNECTIONS = 5;
private ArrayList active = new ArrayList();
private ArrayList queue = new ArrayList();
private static ConnectionManager instance;
public static ConnectionManager getInstance() {
if (instance == null)
instance = new ConnectionManager();
return instance;
}
public void push(Runnable runnable) {
queue.add(runnable);
if (active.size() < MAX_CONNECTIONS)
startNext();
}
private void startNext() {
if (!queue.isEmpty()) {
Runnable next = queue.get(0);
queue.remove(0);
active.add(next);
Thread thread = new Thread(next);
thread.start();
}
}
public void didComplete(Runnable runnable) {
active.remove(runnable);
startNext();
}
}
然后定义一个自己的请求完成处理类:
public class HttpHandler extends Handler {
private Context context;
private ProgressDialog progressDialog;
public HttpHandler(Context context) {
this.context = context;
}
protected void start() {
progressDialog = ProgressDialog.show(context,
"Please Wait...", "processing...", true);
}
protected void succeed(int MsgType, Object obj) {
if(progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}
protected void timeout() {
}
protected void otherHandleMessage(Message message){
}
public void handleMessage(Message message) {
switch (message.what) {
case HttpConnectionUtils.DID_START: //connection start
Log.d(context.getClass().getSimpleName(),
"http connection start...");
start();
break;
case HttpConnectionUtils.DID_SUCCEED: //connection success
progressDialog.dismiss();
succeed(message.arg1, message.obj);
break;
case HttpConnectionUtils.DID_ERROR: //connection error
if(progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
Exception e = (Exception) message.obj;
e.printStackTrace();
Log.e(context.getClass().getSimpleName(), "connection fail."
+ e.getMessage());
Toast.makeText(context, "connection fail,please check connection!",
Toast.LENGTH_LONG).show();
break;
}
otherHandleMessage(message);
}
}