HttpConnectionUtils 支持get post put delete請求 圖片請求
- /**
- * HTTP connection helper
- * @author
- *
- */
- 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;
- 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 Handler handler;
- private List<NameValuePair> data;
- private HttpClient httpClient;
- public HttpConnectionUtils() {
- this(new Handler());
- }
- public HttpConnectionUtils(Handler _handler) {
- handler = _handler;
- }
- public void create(int method, String url, List<NameValuePair> data) {
- Log.d(TAG, "method:"+method+" ,url:"+url+" ,data:"+data);
- this.method = method;
- this.url = url;
- this.data = data;
- ConnectionManager.getInstance().push(this);
- }
- public void get(String url) {
- create(GET, url, null);
- }
- public void post(String url, List<NameValuePair> data) {
- create(POST, url, data);
- }
- public void put(String url, List<NameValuePair> data) {
- create(PUT, url, data);
- }
- public void delete(String url) {
- create(DELETE, url, null);
- }
- public void bitmap(String url) {
- create(BITMAP, url, null);
- }
- @Override
- public void run() {
- handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_START));
- httpClient = new DefaultHttpClient();
- HttpConnectionParams
- .setConnectionTimeout(httpClient.getParams(), 6000);
- try {
- HttpResponse response = null;
- switch (method) {
- case GET:
- response = httpClient.execute(new HttpGet(url));
- break;
- case POST:
- HttpPost httpPost = new HttpPost(url);
- httpPost.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));
- response = httpClient.execute(httpPost);
- break;
- case PUT:
- HttpPut httpPut = new HttpPut(url);
- httpPut.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));
- response = httpClient.execute(httpPut);
- break;
- case DELETE:
- response = httpClient.execute(new HttpDelete(url));
- break;
- case BITMAP:
- response = httpClient.execute(new HttpGet(url));
- processBitmapEntity(response.getEntity());
- break;
- }
- if (method < BITMAP)
- processEntity(response.getEntity());
- } catch (Exception e) {
- handler.sendMessage(Message.obtain(handler,
- HttpConnectionUtils.DID_ERROR, e));
- }
- ConnectionManager.getInstance().didComplete(this);
- }
- private void processEntity(HttpEntity entity) throws IllegalStateException,
- IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(entity
- .getContent()));
- String line, result = "";
- while ((line = br.readLine()) != null)
- result += line;
- Message message = Message.obtain(handler, DID_SUCCEED, result);
- handler.sendMessage(message);
- }
- private void processBitmapEntity(HttpEntity entity) throws IOException {
- BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
- Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
- handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));
- }
/**
* HTTP connection helper
* @author
*
*/
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;
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 Handler handler;
private List<NameValuePair> data;
private HttpClient httpClient;
public HttpConnectionUtils() {
this(new Handler());
}
public HttpConnectionUtils(Handler _handler) {
handler = _handler;
}
public void create(int method, String url, List<NameValuePair> data) {
Log.d(TAG, "method:"+method+" ,url:"+url+" ,data:"+data);
this.method = method;
this.url = url;
this.data = data;
ConnectionManager.getInstance().push(this);
}
public void get(String url) {
create(GET, url, null);
}
public void post(String url, List<NameValuePair> data) {
create(POST, url, data);
}
public void put(String url, List<NameValuePair> data) {
create(PUT, url, data);
}
public void delete(String url) {
create(DELETE, url, null);
}
public void bitmap(String url) {
create(BITMAP, url, null);
}
@Override
public void run() {
handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_START));
httpClient = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(httpClient.getParams(), 6000);
try {
HttpResponse response = null;
switch (method) {
case GET:
response = httpClient.execute(new HttpGet(url));
break;
case POST:
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));
response = httpClient.execute(httpPost);
break;
case PUT:
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));
response = httpClient.execute(httpPut);
break;
case DELETE:
response = httpClient.execute(new HttpDelete(url));
break;
case BITMAP:
response = httpClient.execute(new HttpGet(url));
processBitmapEntity(response.getEntity());
break;
}
if (method < BITMAP)
processEntity(response.getEntity());
} catch (Exception e) {
handler.sendMessage(Message.obtain(handler,
HttpConnectionUtils.DID_ERROR, e));
}
ConnectionManager.getInstance().didComplete(this);
}
private void processEntity(HttpEntity entity) throws IllegalStateException,
IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(entity
.getContent()));
String line, result = "";
while ((line = br.readLine()) != null)
result += line;
Message message = Message.obtain(handler, DID_SUCCEED, result);
handler.sendMessage(message);
}
private void processBitmapEntity(HttpEntity entity) throws IOException {
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));
}
ConnectionManager
- public class ConnectionManager {
- public static final int MAX_CONNECTIONS = 5;
- private ArrayList<Runnable> active = new ArrayList<Runnable>();
- private ArrayList<Runnable> queue = new ArrayList<Runnable>();
- 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 ConnectionManager {
public static final int MAX_CONNECTIONS = 5;
private ArrayList<Runnable> active = new ArrayList<Runnable>();
private ArrayList<Runnable> queue = new ArrayList<Runnable>();
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();
}
}
封裝的Handler HttpHandler 也可以自己處理
- 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(JSONObject jObject) {
- if(progressDialog!=null && progressDialog.isShowing()){
- progressDialog.dismiss();
- }
- }
- protected void failed(JSONObject jObject) {
- if(progressDialog!=null && progressDialog.isShowing()){
- progressDialog.dismiss();
- }
- }
- 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();
- String response = (String) message.obj;
- Log.d(context.getClass().getSimpleName(), "http connection return."
- + response);
- try {
- JSONObject jObject = new JSONObject(response == null ? ""
- : response.trim());
- if ("true".equals(jObject.getString("success"))) { //operate success
- Toast.makeText(context, "operate succeed:"+jObject.getString("msg"),Toast.LENGTH_SHORT).show();
- succeed(jObject);
- } else {
- Toast.makeText(context, "operate fialed:"+jObject.getString("msg"),Toast.LENGTH_LONG).show();
- failed(jObject);
- }
- } catch (JSONException e1) {
- if(progressDialog!=null && progressDialog.isShowing()){
- progressDialog.dismiss();
- }
- e1.printStackTrace();
- Toast.makeText(context, "Response data is not json data",
- Toast.LENGTH_LONG).show();
- }
- 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);
- }
- }
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(JSONObject jObject) {
if(progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}
protected void failed(JSONObject jObject) {
if(progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}
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();
String response = (String) message.obj;
Log.d(context.getClass().getSimpleName(), "http connection return."
+ response);
try {
JSONObject jObject = new JSONObject(response == null ? ""
: response.trim());
if ("true".equals(jObject.getString("success"))) { //operate success
Toast.makeText(context, "operate succeed:"+jObject.getString("msg"),Toast.LENGTH_SHORT).show();
succeed(jObject);
} else {
Toast.makeText(context, "operate fialed:"+jObject.getString("msg"),Toast.LENGTH_LONG).show();
failed(jObject);
}
} catch (JSONException e1) {
if(progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
e1.printStackTrace();
Toast.makeText(context, "Response data is not json data",
Toast.LENGTH_LONG).show();
}
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);
}
}
我這兒server端返回的數據都是json格式。必須包括{success:"true",msg:"xxx",other:xxx} 操作成功success爲true.
調用的代碼:
- private Handler handler = new HttpHandler(LoginActivity.this) {
- @Override
- protected void succeed(JSONObject jObject) { //自己處理成功後的操作
- super.succeed(jObject);
- } //也可以在這重寫start() failed()方法
- };
- private void login() {
- ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("email", loginEmail.getText().toString()));
- params.add(new BasicNameValuePair("password", loginPassword.getText().toString()));
- String urlString = HttpConnectionUtils.getUrlFromResources(LoginActivity.this, R.string.login_url);
- new HttpConnectionUtils(handler).post(urlString, params);
- }