5.AsyncHttp、post

httpClient

	// 网络访问请求
 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;
						}
					}
				});

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 13.json解析

    六月的雨
  • 7.Android常用第三方支付

    六月的雨
  • 16.IO之其他流

    六月的雨
  • Java利用多线程和Socket制作GUI界面的在线聊天室

    最近刚好是期末,碰上Java实训,借此将之前写的在线聊天室搬出来,加上GUI(Swing),当成实训作品,记录一下这次实训的结果。

    HcodeBlogger
  • 聊聊nacos client的PushReceiver

    nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/naming/core/PushReceiv...

    codecraft
  • 聊聊nacos client的PushReceiver

    nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/naming/core/PushReceiv...

    codecraft
  • 微信扫码支付

    一,需要申请公司的微信公众号,以及商户号。然后在商户号中关联微信公众APPID。在商户平台添加扫码支付功能。

    故久
  • 项目工具类

    一、前言     在工作中,难免遇到各种各样的问题,每个人似乎都有一套自己的解决方案。而我,又不想每次解决完问题就把东西扔了,捡了芝麻,丢了西瓜,什么时候才能进...

    JMCui
  • 获取压缩包中的文本字符串。

    通过指定位置压缩包解析公钥,和密文,解析客户信息,不需要解压,那是我手动解压看效果的。 ps:中文可能会产生乱码,调一下编码。

    崔笑颜
  • dubbo监控机制之监控中心实现分析

    github 地址 https://github.com/apache/dubbo-admin ,被单独移到dubbo-admin中维护,在master 分支中

    技术蓝海

扫码关注云+社区

领取腾讯云代金券