// 网络访问请求
new Thread(new Runnable() {
@Override
public void run() {
String url = "http://192.168.1.101:8080/ChatServer/register";
// 创建 httpClient
HttpClient client = new DefaultHttpClient();
// 创建 post请求
HttpPost post = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
// 配置请求头
// post.addHeader("", "");
// 配置请求参数
pairs.add(new BasicNameValuePair("account", account));
pairs.add(new BasicNameValuePair("password", password));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// 拿到网络的返回结果
final String result = EntityUtils.toString(response
.OgetEntity());
Log.d("result : ", "" + result);
// 需要在主线线程中做UI操作
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
doResult(result);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
AsyncHttp
// 创建 访问端
AsyncHttpClient client = new AsyncHttpClient();
// 接口地址
String url = "http://192.168.1.101:8080/ChatServer/register";
//
RequestParams params = new RequestParams();
params.put("account", account);
params.put("password", password);
// 调用post方法访问网络
client.post(context, url, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Log.d("success", responseString + "");
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(responseString);
JsonObject root = element.getAsJsonObject();
JsonPrimitive flagJson = root.getAsJsonPrimitive("flag");
boolean flag = flagJson.getAsBoolean();
if (flag) {
JsonObject dataObject = root.getAsJsonObject("data");
if (dataObject != null) {
Account user = new Gson().fromJson(dataObject,
Account.class);
Log.d("", user.toString());
}
} else {
JsonPrimitive errorCodeJson = root
.getAsJsonPrimitive("errorCode");
JsonPrimitive errorStringJson = root
.getAsJsonPrimitive("errorString");
Log.d("", errorCodeJson.getAsInt() + " : "
+ errorStringJson.getAsString());
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
Log.d("error", responseString + " : " + throwable.getMessage());
}
});
由于不需要每个页面访问网络都去写这一段代码,抽取:
回调接口:
public abstract class ObjectCallback<T> {
private final Class<T> clazz;
@SuppressWarnings("unchecked")
public ObjectCallback() {
ParameterizedType type = (ParameterizedType) this.getClass()
.getGenericSuperclass();
clazz = (Class<T>) type.getActualTypeArguments()[0];//获取泛型
}
public Class<T> getDataClass() {
return clazz;
}
public abstract void onSuccess(T data);
public abstract void onFailure(int errorCode, String errorString);
}
HMChatManager
public class HMChatManager {
private static HMChatManager instance;
private Context context;
public static HMChatManager getInstance(Context context) {
if (instance == null) {
synchronized (HMChatManager.class) {
if (instance == null) {
instance = new HMChatManager(context);
}
}
}
return instance;
}
private HMChatManager(Context context) {
this.context = context;
}
@SuppressWarnings("rawtypes")
public HttpFuture sendRequest(String url, final ObjectCallback callback) {
return sendRequest(url, null, callback);
}
@SuppressWarnings("rawtypes")
public HttpFuture sendRequest(String url, Map<String, String> headers,
Map<String, String> paramters, final ObjectCallback callback) {
// 创建 访问端
AsyncHttpClient client = new AsyncHttpClient();
// 请求消息头
if (headers != null) {
for (Map.Entry<String, String> me : headers.entrySet()) {
client.addHeader(me.getKey(), me.getValue());
}
}
// 请求参数
RequestParams params = new RequestParams();
// params.put("account", account);
// params.put("password", password);
if (paramters != null) {
for (Map.Entry<String, String> me : paramters.entrySet()) {
params.put(me.getKey(), me.getValue());
}
}
// 调用post方法访问网络
RequestHandle handle = client.post(context, url, params,
new TextHttpResponseHandler() {
@SuppressWarnings("unchecked")
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Log.d("success", responseString + "");
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(responseString);
JsonObject root = element.getAsJsonObject();
JsonPrimitive flagJson = root
.getAsJsonPrimitive("flag");
boolean flag = flagJson.getAsBoolean();
if (flag) {
JsonObject dataObject = root
.getAsJsonObject("data");
if (dataObject != null) {
if (callback != null) {
@SuppressWarnings("unchecked")
Object obj = new Gson().fromJson(
dataObject, callback.getDataClass());
callback.onSuccess(obj);
}
}
} else {
JsonPrimitive errorCodeJson = root
.getAsJsonPrimitive("errorCode");
JsonPrimitive errorStringJson = root
.getAsJsonPrimitive("errorString");
Log.d("", errorCodeJson.getAsInt() + " : "
+ errorStringJson.getAsString());
if (callback != null) {
callback.onFailure(errorCodeJson.getAsInt(),
errorStringJson.getAsString());
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
Log.d("error",
responseString + " : " + throwable.getMessage());
if (callback != null) {
callback.onFailure(HMError.ERROR_SERVER, "服务器连接问题");
}
}
});
return new HttpFuture(handle);
}
访问的的时候
String url = "http://192.168.1.101:8080/ChatServer/register";
Map<String, String> paramters = new HashMap<String, String>();
paramters.put("account", account);
paramters.put("password", password);
future = HMChatManager.getInstance(getActivity()).sendRequest(url,
paramters, new ObjectCallback<Account>() {
@Override
public void onSuccess(Account data) {
Log.d("onSuccess", data.toString());
// 数据的存储
AccountDao dao = new AccountDao(getActivity());
data.setCurrent(true);
Account localAccount = dao.getByAccount(data
.getAccount());
if (localAccount != null) {
dao.updateAccount(data);
} else {
dao.addAccount(data);
}
// 页面跳转
((LoginActivity) getActivity()).go2FillInfo();
}
@Override
public void onFailure(int errorCode, String errorString) {
Log.d("onFailure", errorCode + " : " + errorString);
switch (errorCode) {
case HMError.ERROR_CLIENT_NET:
Log.d(TAG, "客户端网络异常");
ToastUtil.show(getActivity(), "客户端网络异常");
break;
case HMError.ERROR_SERVER:
Log.d(TAG, "服务器异常");
ToastUtil.show(getActivity(), "服务器异常");
break;
case HMError.Register.ACCOUNT_EXIST:
Log.d(TAG, "用户已经存在");
ToastUtil.show(getActivity(), "用户已经存在");
break;
default:
break;
}
}
});