您的位置:首页 > 理论基础 > 计算机网络

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;
}
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: