NetUtil.java
package com.gzucm.volunteer.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.gzucm.volunteer.R;
import com.gzucm.volunteer.vo.RequestVo;
public class NetUtil {
private static final String NOT_LOGIN = "notlogin";
private static final String TAG = "NetUtil";
private static Header[] headers = new BasicHeader[11]; //传递时候的头信息
static {
headers[0] = new BasicHeader("Appkey", "");
headers[1] = new BasicHeader("Udid", "");
headers[2] = new BasicHeader("Os", "");
headers[3] = new BasicHeader("Osversion", "");
headers[4] = new BasicHeader("Appversion", "");
headers[5] = new BasicHeader("Sourceid", "");
headers[6] = new BasicHeader("Ver", "");
headers[7] = new BasicHeader("Userid", "");
headers[8] = new BasicHeader("Usersession", "");
headers[9] = new BasicHeader("Unique", "");
headers[10] = new BasicHeader("Cookie", "");
}
public static Header[] getHeaders() {
return headers;
}
public static Object post(RequestVo vo) {
DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);// 请求超时
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); //读取超时
String url = vo.context.getString(R.string.app_host).concat(vo.context.getString(vo.requestUrl));
Logger.d(TAG, "Post " + url);
HttpPost post = new HttpPost(url);
post.setHeaders(headers);
Object obj = null;
try {
if (vo.requestDataMap != null) {
HashMap<String, String> map = vo.requestDataMap;
ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
pairList.add(pair);
}
HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
post.setEntity(entity);
}
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
setCookie(response);
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
try {
if (invilidateLogin(result)) { //验证是否登录成功
return Status.Login; //登录失败,需要重新登录
}
obj = vo.jsonParser.parseJSON(result);
} catch (JSONException e) {
Logger.e(TAG, e.getLocalizedMessage(), e);
}
return obj;
}
} catch (ClientProtocolException e) {
Logger.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Logger.e(TAG, e.getLocalizedMessage(), e);
}
return null;
}
/**
* 添加Cookie
* @param response
*/
public static void setCookie(HttpResponse response) {
if (response.getHeaders("Set-Cookie").length > 0) {
Logger.d(TAG, response.getHeaders("Set-Cookie")[0].getValue()) ;
headers[10] = new BasicHeader("Cookie", response.getHeaders("Set-Cookie")[0].getValue());
}
}
/**
* 验证是否需要登录
* @param result
* @return
* @throws JSONException
*/
public static boolean invilidateLogin(String result) throws JSONException {
JSONObject jsonObject = new JSONObject(result);
String responseCode = jsonObject.getString("response");
if (NOT_LOGIN.equals(responseCode)) {
return true;
}
return false;
}
/**
*
* @param vo
* @return
*/
public static Object get(RequestVo vo) {
DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);// 请求超时
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); //读取超时
String url = vo.context.getString(R.string.app_host).concat(vo.context.getString(vo.requestUrl));
Logger.d(TAG, "Get " + url);
HttpGet get = new HttpGet(url);
get.setHeaders(headers);
Object obj = null;
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
setCookie(response);
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
Logger.d(TAG, result);
try {
if (invilidateLogin(result)) {
return Status.Login;
}
obj = vo.jsonParser.parseJSON(result);
} catch (JSONException e) {
Logger.e(TAG, e.getLocalizedMessage(), e);
}
return obj;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获得网络连接是否可用
*
* @param context
* @return
*/
public static boolean hasNetwork(Context context) {
ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo workinfo = con.getActiveNetworkInfo();
if (workinfo == null || !workinfo.isAvailable()) {
Logger.d(TAG, "网络不可用");
return false;
}
return true;
}
public static enum Status {
Login
}
}
其中请求参数类
RequestVo.java
package com.gzucm.volunteer.vo;
import java.util.HashMap;
import com.gzucm.volunteer.parser.BaseParser;
import android.content.Context;
public class RequestVo {
public int requestUrl; //访问服务器的地址,除去主机地址之后
public Context context; //上下文
public HashMap<String, String> requestDataMap; //传递的参数
public BaseParser<?> jsonParser; //回调方法
public RequestVo() {
}
public RequestVo(int requestUrl, Context context, HashMap<String, String> requestDataMap, BaseParser<?> jsonParser) {
super();
this.requestUrl = requestUrl;
this.context = context;
this.requestDataMap = requestDataMap;
this.jsonParser = jsonParser;
}
}
BaseParser.java
package com.gzucm.volunteer.parser;
import org.json.JSONException;
import org.json.JSONObject;
/*回调方法*/
public abstract class BaseParser<T> {
/**
* 将返回的json数据转化为相应的对象
* @param paramString
* @throws JSONException
*/
public abstract T parseJSON(String paramString) throws JSONException;
/**
* 检测服务器响应信息,并返回response中的内容-----处理的servlet名
* @param paramString
* @throws JSONException
*/
public String checkResponse(String paramString) throws JSONException {
if (paramString == null) {
return null;
} else {
JSONObject jsonObject = new JSONObject(paramString);
String result = jsonObject.getString("response");
if (result != null && !result.equals("error")) {
return result;
} else {
return null;
}
}
}
}
RequestVo vo = new RequestVo();
vo.requestUrl = R.string.login; //登录的servlet名称
vo.jsonParser = new LoginParser();
vo.context = this;
HashMap map = new HashMap();
map.put("username", userName);
vo.requestDataMap = map;
super.getDataFromServer(vo, new DataCallback<User>(){
@Override
public void processData(User paramObject,boolean paramBoolean) {
}
});
其中要继承基类Activity
主要代码:
/**
* 显示进度框
*/
protected void showProgressDialog() {
if ((!isFinishing()) && (this.progressDialog == null)) {
this.progressDialog = new ProgressDialog(this);
}
this.progressDialog.setTitle(getString(R.string.loadTitle));
this.progressDialog.setMessage(getString(R.string.LoadContent));
this.progressDialog.show();
}
/**
* 隐藏进度框
*/
protected void closeProgressDialog() {
if (this.progressDialog != null)
this.progressDialog.dismiss();
}
/* 回调方法处理请求 */
@SuppressWarnings("unchecked")
class BaseHandler extends Handler {
private Context context;
private DataCallback callBack;
private RequestVo reqVo;
public BaseHandler(Context context, DataCallback callBack,
RequestVo reqVo) {
this.context = context;
this.callBack = callBack;
this.reqVo = reqVo;
}
public void handleMessage(Message msg) {
closeProgressDialog();
if (msg.what == Constant.SUCCESS) {
if (msg.obj == null) {
Toast.makeText(context, getString(R.string.net_server_no_respone), Toast.LENGTH_SHORT).show();// 服务器未响应对话框
} else {
callBack.processData(msg.obj, true);
}
} else if (msg.what == Constant.NET_FAILED) {
Toast.makeText(context, getString(R.string.net_error), Toast.LENGTH_SHORT).show(); //网络未连接
}
Logger.d(TAG, "recordSize:" + record.size());
}
}
/* 处理登陆的子线程 */
class BaseTask implements Runnable {
private Context context;
private RequestVo reqVo;
private Handler handler;
public BaseTask(Context context, RequestVo reqVo, Handler handler) {
this.context = context;
this.reqVo = reqVo;
this.handler = handler;
}
@Override
public void run() {
Object obj = null;
Message msg = Message.obtain();
try {
if (NetUtil.hasNetwork(context)) {
obj = NetUtil.post(reqVo);
if (obj instanceof Status) {
Intent intent = new Intent(BaseWapperActivity.this,
LoginActivity.class);
intent.putExtra("notlogin", "notlogin");
startActivityForResult(intent, NOT_LOGIN);
} else {
msg.what = Constant.SUCCESS;
msg.obj = obj;
handler.sendMessage(msg);
record.remove(this);
}
} else {
msg.what = Constant.NET_FAILED;
msg.obj = obj;
handler.sendMessage(msg);
record.remove(this);
}
} catch (Exception e) {
record.remove(this);
throw new RuntimeException(e);
}
}
}
/**
* 回调函数,处理服务器返回的数据
*
* @param paramObject
* 服务器返回的数据封装后的对象
* @param paramBoolean
* 服务器是否返回数据
*/
public abstract interface DataCallback<T> {
public abstract void processData(T paramObject, boolean paramBoolean);
}
/**
* 向服务器发送请求
*
* @param reqVo
* @param callBack
*/
protected void getDataFromServer(RequestVo reqVo, DataCallback callBack) {
showProgressDialog();
BaseHandler handler = new BaseHandler(this, callBack, reqVo);
BaseTask taskThread = new BaseTask(this, reqVo, handler);
this.threadPoolManager.addTask(taskThread);
}
该源码框架取自红孩子应用程序