AsyncHttpClient的使用
mync
9年前
不要做代码的轮子
与其重复的写代码,不如利用别人写好的代码开发时更节省时间,最近从github上下载了一套代码,http异步请求get,post请求,也可以用作文件上传,很方便,感觉比较好,推荐给大家用
以登录为例,代码写的可能不太好,试着应用一下
AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.add("RequestType", ""); params.add("UserID", "-1"); params.add("NurseID", "-1"); params.add("HospitalId", "-1"); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("UserCode", username); jsonObject.put("Password", password); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } params.add("RequestParam", jsonObject.toString()); client.get(path, params, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { // TODO Auto-generated method stub if (statusCode == 200) { // Toast.makeText(getApplicationContext(), // responseString, Toast.LENGTH_SHORT) // .show(); Intent intent = new Intent(); intent.setClass( getApplicationContext(), MainActivity.class); startActivity(intent); } else { Intent intent = new Intent(); intent.setClass( getApplicationContext(), MainActivity.class); startActivity(intent); } } else { Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { Toast.makeText(getApplicationContext(), "网络连接超时", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), responseString, Toast.LENGTH_SHORT).show(); }
1.声明一个client对象,初始化
2.根据需要调用client中get,post请求
3,重写onSuccess()和onFailure()方法
注:在https://github.com/AsyncHttpClient/async-http-client下载包,直接将library下的包直接粘贴到项目src下,直接调用即可