5.AsyncHttp、post

httpClient
  1. // 网络访问请求
  2. new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. String url = "http://192.168.1.101:8080/ChatServer/register";
  6. // 创建 httpClient
  7. HttpClient client = new DefaultHttpClient();
  8. // 创建 post请求
  9. HttpPost post = new HttpPost(url);
  10. List<NameValuePair> pairs = new ArrayList<NameValuePair>();
  11. // 配置请求头
  12. // post.addHeader("", "");
  13. // 配置请求参数
  14. pairs.add(new BasicNameValuePair("account", account));
  15. pairs.add(new BasicNameValuePair("password", password));
  16. try {
  17. post.setEntity(new UrlEncodedFormEntity(pairs));
  18. HttpResponse response = client.execute(post);
  19. int statusCode = response.getStatusLine().getStatusCode();
  20. if (statusCode == 200) {
  21. // 拿到网络的返回结果
  22. final String result = EntityUtils.toString(response
  23. .OgetEntity());
  24. Log.d("result : ", "" + result);
  25. // 需要在主线线程中做UI操作
  26. getActivity().runOnUiThread(new Runnable() {
  27. @Override
  28. public void run() {
  29. doResult(result);
  30. }
  31. });
  32. }
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }).start();
AsyncHttp
  1. // 创建 访问端
  2. AsyncHttpClient client = new AsyncHttpClient();
  3. // 接口地址
  4. String url = "http://192.168.1.101:8080/ChatServer/register";
  5. //
  6. RequestParams params = new RequestParams();
  7. params.put("account", account);
  8. params.put("password", password);
  9. // 调用post方法访问网络
  10. client.post(context, url, params, new TextHttpResponseHandler() {
  11. @Override
  12. public void onSuccess(int statusCode, Header[] headers,
  13. String responseString) {
  14. Log.d("success", responseString + "");
  15. JsonParser parser = new JsonParser();
  16. JsonElement element = parser.parse(responseString);
  17. JsonObject root = element.getAsJsonObject();
  18. JsonPrimitive flagJson = root.getAsJsonPrimitive("flag");
  19. boolean flag = flagJson.getAsBoolean();
  20. if (flag) {
  21. JsonObject dataObject = root.getAsJsonObject("data");
  22. if (dataObject != null) {
  23. Account user = new Gson().fromJson(dataObject,
  24. Account.class);
  25. Log.d("", user.toString());
  26. }
  27. } else {
  28. JsonPrimitive errorCodeJson = root
  29. .getAsJsonPrimitive("errorCode");
  30. JsonPrimitive errorStringJson = root
  31. .getAsJsonPrimitive("errorString");
  32. Log.d("", errorCodeJson.getAsInt() + " : "
  33. + errorStringJson.getAsString());
  34. }
  35. }
  36. @Override
  37. public void onFailure(int statusCode, Header[] headers,
  38. String responseString, Throwable throwable) {
  39. Log.d("error", responseString + " : " + throwable.getMessage());
  40. }
  41. });
由于不需要每个页面访问网络都去写这一段代码,抽取:

回调接口:
  1. public abstract class ObjectCallback<T> {
  2. private final Class<T> clazz;
  3. @SuppressWarnings("unchecked")
  4. public ObjectCallback() {
  5. ParameterizedType type = (ParameterizedType) this.getClass()
  6. .getGenericSuperclass();
  7. clazz = (Class<T>) type.getActualTypeArguments()[0];//获取泛型
  8. }
  9. public Class<T> getDataClass() {
  10. return clazz;
  11. }
  12. public abstract void onSuccess(T data);
  13. public abstract void onFailure(int errorCode, String errorString);
  14. }
HMChatManager 
  1. public class HMChatManager {
  2. private static HMChatManager instance;
  3. private Context context;
  4. public static HMChatManager getInstance(Context context) {
  5. if (instance == null) {
  6. synchronized (HMChatManager.class) {
  7. if (instance == null) {
  8. instance = new HMChatManager(context);
  9. }
  10. }
  11. }
  12. return instance;
  13. }
  14. private HMChatManager(Context context) {
  15. this.context = context;
  16. }
  17. @SuppressWarnings("rawtypes")
  18. public HttpFuture sendRequest(String url, final ObjectCallback callback) {
  19. return sendRequest(url, null, callback);
  20. }
  21. @SuppressWarnings("rawtypes")
  22. public HttpFuture sendRequest(String url, Map<String, String> headers,
  23. Map<String, String> paramters, final ObjectCallback callback) {
  24. // 创建 访问端
  25. AsyncHttpClient client = new AsyncHttpClient();
  26. // 请求消息头
  27. if (headers != null) {
  28. for (Map.Entry<String, String> me : headers.entrySet()) {
  29. client.addHeader(me.getKey(), me.getValue());
  30. }
  31. }
  32. // 请求参数
  33. RequestParams params = new RequestParams();
  34. // params.put("account", account);
  35. // params.put("password", password);
  36. if (paramters != null) {
  37. for (Map.Entry<String, String> me : paramters.entrySet()) {
  38. params.put(me.getKey(), me.getValue());
  39. }
  40. }
  41. // 调用post方法访问网络
  42. RequestHandle handle = client.post(context, url, params,
  43. new TextHttpResponseHandler() {
  44. @SuppressWarnings("unchecked")
  45. @Override
  46. public void onSuccess(int statusCode, Header[] headers,
  47. String responseString) {
  48. Log.d("success", responseString + "");
  49. JsonParser parser = new JsonParser();
  50. JsonElement element = parser.parse(responseString);
  51. JsonObject root = element.getAsJsonObject();
  52. JsonPrimitive flagJson = root
  53. .getAsJsonPrimitive("flag");
  54. boolean flag = flagJson.getAsBoolean();
  55. if (flag) {
  56. JsonObject dataObject = root
  57. .getAsJsonObject("data");
  58. if (dataObject != null) {
  59. if (callback != null) {
  60. @SuppressWarnings("unchecked")
  61. Object obj = new Gson().fromJson(
  62. dataObject, callback.getDataClass());
  63. callback.onSuccess(obj);
  64. }
  65. }
  66. } else {
  67. JsonPrimitive errorCodeJson = root
  68. .getAsJsonPrimitive("errorCode");
  69. JsonPrimitive errorStringJson = root
  70. .getAsJsonPrimitive("errorString");
  71. Log.d("", errorCodeJson.getAsInt() + " : "
  72. + errorStringJson.getAsString());
  73. if (callback != null) {
  74. callback.onFailure(errorCodeJson.getAsInt(),
  75. errorStringJson.getAsString());
  76. }
  77. }
  78. }
  79. @Override
  80. public void onFailure(int statusCode, Header[] headers,
  81. String responseString, Throwable throwable) {
  82. Log.d("error",
  83. responseString + " : " + throwable.getMessage());
  84. if (callback != null) {
  85. callback.onFailure(HMError.ERROR_SERVER, "服务器连接问题");
  86. }
  87. }
  88. });
  89. return new HttpFuture(handle);
  90. }
访问的的时候
  1. String url = "http://192.168.1.101:8080/ChatServer/register";
  2. Map<String, String> paramters = new HashMap<String, String>();
  3. paramters.put("account", account);
  4. paramters.put("password", password);
  5. future = HMChatManager.getInstance(getActivity()).sendRequest(url,
  6. paramters, new ObjectCallback<Account>() {
  7. @Override
  8. public void onSuccess(Account data) {
  9. Log.d("onSuccess", data.toString());
  10. // 数据的存储
  11. AccountDao dao = new AccountDao(getActivity());
  12. data.setCurrent(true);
  13. Account localAccount = dao.getByAccount(data
  14. .getAccount());
  15. if (localAccount != null) {
  16. dao.updateAccount(data);
  17. } else {
  18. dao.addAccount(data);
  19. }
  20. // 页面跳转
  21. ((LoginActivity) getActivity()).go2FillInfo();
  22. }
  23. @Override
  24. public void onFailure(int errorCode, String errorString) {
  25. Log.d("onFailure", errorCode + " : " + errorString);
  26. switch (errorCode) {
  27. case HMError.ERROR_CLIENT_NET:
  28. Log.d(TAG, "客户端网络异常");
  29. ToastUtil.show(getActivity(), "客户端网络异常");
  30. break;
  31. case HMError.ERROR_SERVER:
  32. Log.d(TAG, "服务器异常");
  33. ToastUtil.show(getActivity(), "服务器异常");
  34. break;
  35. case HMError.Register.ACCOUNT_EXIST:
  36. Log.d(TAG, "用户已经存在");
  37. ToastUtil.show(getActivity(), "用户已经存在");
  38. break;
  39. default:
  40. break;
  41. }
  42. }
  43. });

 

附件列表

     

    posted @ 2016-02-13 17:27  梦和远方  阅读(373)  评论(0编辑  收藏  举报