Android基于http封装的网络请求框架
2017-06-22 14:31
1256 查看
以json的数据类型传给后台,从后台拉取数据的完整例子,其中包括所需要用的封装完整的网络请求HttpClient框架;
step 1:
private class GetActionDataTask extends AsyncTask<Void, Void, List<ActionList>> { @Override protected List<ActionList> doInBackground(Void... sessionid) { showDialog(getResources().getString(R.string.bestgirl_wait)); List<ActionList> actionLists = null; try { if (!"".equals(mSportsApp.getSessionId()) && mSportsApp.getSessionId() != null) { actionLists = ApiJsonParser .getNewActionList( mSportsApp.getSessionId(), "z" + getResources().getString( R.string.config_game_id), 0); } } catch (ApiNetException e) { e.printStackTrace(); } catch (ApiSessionOutException e) { e.printStackTrace(); } return actionLists; } @Override protected void onPostExecute(List<ActionList> result) { super.onPostExecute(result); mLoadProgressDialog.dismiss(); if (result == null) return; if (result.size() > 0 && actionLists != null) { for (ActionList actionList : result) { actionLists.add(actionList); } } } }
step 2:
public static List<ActionList> getNewActionList(String sessionId, String channelnum, int times) throws ApiNetException, ApiSessionOutException { ApiMessage msg = Api.getNewActionList(sessionId, channelnum, times); List<ActionList> lst = null; if (msg.isFlag()) { lst = new ArrayList<ActionList>(); String content = msg.getMsg(); Log.e(TAG, "活动----" + content); try { JSONArray jsonArray = new JSONObject(content) .getJSONArray("data"); ActionList lists = null; if (jsonArray != null && jsonArray.length() > 0) { // 缓存运动秀的数据 if (times == 0) { SharedPreferences preferences = SportsApp.getInstance() .getSharedPreferences("ActionList", 0); Editor edit = preferences.edit(); edit.putString("ActionList_info", content); edit.commit(); } for (int i = 0; i < jsonArray.length(); i++) { lists = new ActionList(); JSONObject obj = jsonArray.getJSONObject(i); lists.actionId = obj.getInt("id"); lists.title = obj.getString("title"); lists.url = obj.getString("thumb"); lists.actionTime = obj.getString("activity_time"); lists.actionUrl = obj.getString("url"); lists.thuurl = obj.getString("thrurl"); if(obj.has("match_act")){ lists.match_act = obj.getInt("match_act"); } if(obj.has("match_url")){ lists.match_url = obj.getString("match_url"); } if (obj.has("match_info")) { if (!"".equals(obj.getString("match_info"))) { JSONObject jsonObject = obj.getJSONObject("match_info"); lists.setMatchId(jsonObject.getInt("id")); lists.setMatchprice(jsonObject.getInt("price")); lists.setMatchTitle(jsonObject.getString("title")); } } lst.add(lists); } } } catch (JSONException e) { e.printStackTrace(); } Log.i(TAG, "action list=" + content); } return lst; }
step 3:
public static ApiMessage getNewActionList(String sessionId, String channelnum, int times) { // TODO Auto-generated method stub JSONObject localJSONObject = new JSONObject(); ApiMessage info = new ApiMessage(); try { String url = ApiConstant.DATA_URL + ApiConstant.getNewActionList; localJSONObject.put("session_id", sessionId); localJSONObject.put("channelnum", channelnum); localJSONObject.put("times", times + ""); info = ApiNetwork.post(url, localJSONObject.toString());//引用封装框架 } catch (Exception e) { e.printStackTrace(); } return info; }
step 4:封装好的HttpClient框架,直接调用。
public class ApiNetwork { public static ApiMessage post(String url, String data) { StringEntity se = null; try { se = new StringEntity("content=" + data, HTTP.UTF_8); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } se.setContentType("application/x-www-form-urlencoded"); return postByEntity(url, se); } public static ApiMessage postByEntity(String url, StringEntity se) { // TODO Auto-generated method stub String returnContent = ""; ApiMessage message = new ApiMessage(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30*1000); httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30*1000); try { httppost.setEntity(se); HttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); String returnXML = EntityUtils.toString(response.getEntity()); returnContent = returnXML; switch (status) { case 200: message.setFlag(true); message.setMsg(returnContent); break; default: Log.e("error", status + returnContent); message.setFlag(false); message.setMsg(status + returnContent); break; } }catch (ConnectTimeoutException e) { e.printStackTrace(); message.setFlag(false); message.setMsg("SocketTimeoutException"); }catch (SocketTimeoutException e) { e.printStackTrace(); message.setFlag(false); message.setMsg("SocketTimeoutException"); } catch (Exception e) { e.printStackTrace(); } return message; } public static ApiMessage get(String url) { String returnContent = ""; ApiMessage message = new ApiMessage(); HttpGet get = new HttpGet(url); HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(get); int status = response.getStatusLine().getStatusCode(); String returnXML = EntityUtils.toString(response.getEntity()); returnContent = returnXML; switch (status) { case 200: message.setFlag(true); message.setMsg(returnContent); break; default: Log.e("error", status + returnContent); message.setFlag(false); message.setMsg(status + returnContent); break; } } catch (Exception e) { e.printStackTrace(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("err", "unknown"); returnContent = jsonObject.toString(); message.setFlag(false); message.setMsg(returnContent); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return message; } }
//返回数据的bean类
public class ApiMessage { public boolean flag; public String msg; public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
相关文章推荐
- Android----------OkHttp网络请求框架Get和Post简单封装(泛型)
- android http——网络请求二次封装的框架设计
- Android基于OkHttpUtils网络请求的二次封装
- 使用android-async-http来封装Android网络请求框架
- android基于开源网络框架asychhttpclient,二次封装为通用网络请求组件
- Android 网络请求框架,包涵get,post请求,from表单上传图片,基于okhtt封装的图片上传
- [置顶] 优雅设计封装基于Okhttp3的网络框架(完):原生HttpUrlConnction请求、多线程分发 及 数据转换
- Android基于http的网络请求async-http框架
- android基于开源网络框架asychhttpclient,二次封装为通用网络请求组件
- Android网络请求框架AsyncHttp二次封装
- android http——网络请求二次封装的框架设计
- Android网络请求框架AsyncHttpClient (android-async-http)介绍说明
- 关于android-async-http的使用,封装网络请求
- 完全开源Android网络框架 — 基于JAVA原生的HTTP框架
- 浅论Android网络请求库——android-async-http(比较好的开源框架)
- android网络请求框架 HttpClient与Volley的性能对比
- Android---Xutils3.0 网络请求框架封装(包含解析)
- 优雅设计封装基于Okhttp3的网络框架(一):Http网络协议与Okhttp3解析
- Android网络请求框架----Okhttp3完全解析(2),封装框架
- Android 的OkHttp 网络请求框架的学习封装