您的位置:首页 > 运维架构 > 网站架构

关于Activity获取数据架构的总结

2012-11-26 11:09 363 查看
很简单的架构,但是还是总结一下,落实下来以后项目这样做



如图 ,Activity只是负责和NetService交互获取各种String , 对象 , list等数据,用以显示在Activity中

NetService负责向HttpUtil发送各种url和请求参数 获取的数据交给Activity 如果遇到异常 如网络超时,就直接做异常处理 本案例是显示个Toast

此外 这样的好处也可以使用tesCase直接测试NetService类 ,一部分初级程序员可以只负责Activity的展示,另一部分之负责应用的数据获取以及与服务器的交互,可以细化分工

代码

package com.example.mynetutil;

import java.util.HashMap;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NetService netService = new NetService(this);

String url = "http://192.168.1.177/zwork/test.php";
HashMap<String, String> map = new HashMap<String, String>();
map.put("goods_id", "100078");
map.put("cat_id", "100088");
netService.doSomething(url, map);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}


package com.example.mynetutil;

import java.util.HashMap;

import android.content.Context;
import android.widget.Toast;

public class NetService {

/**
* Capsule all kinds of api requests here
* Your activities only get informations from here rather than httpUtil.
*  @author sfshine
*/
private Context context;

public NetService(Context context) {
super();
this.context = context;
}
/**
* Your api operation and return a object
* @param url
* @param map
*/
public Object doSomething(String url, HashMap<String, String> map) {
String result = HttpUtil.post(url, map);
if ("408timeout".equals(result)) {
showTips("网络超时");
}
else {
//do web logic eg,fetch a object from a json
}

}
/**
* Show some error with toasts
* @param content
*/
public void showTips(String content) {
Toast.makeText(context, content, 1).show();
}
}


package com.example.mynetutil;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

/**
* HttpUtil Class Capsule Most Functions of Http Operations
*
* @author sfshine
*
*/
public class HttpUtil {

private static Header[] headers = new BasicHeader[11];
private static String TAG = "HTTPUTIL";
private static int TIMEOUT = 10 * 1000;

/**
* Your header of http op
*/
static {
headers[0] = new BasicHeader("Appkey", "");
headers[1] = new BasicHeader("Udid", "");
headers[2] = new BasicHeader("Os", "");
headers[3] = new BasicHeader("Osversion", "");
headers[4] = new BasicHeader("Appversion", "");
headers[5] = new BasicHeader("Sourceid", "");
headers[6] = new BasicHeader("Ver", "");
headers[7] = new BasicHeader("Userid", "");
headers[8] = new BasicHeader("Usersession", "");
headers[9] = new BasicHeader("Unique", "");
headers[10] = new BasicHeader("Cookie", "");

}

/**
* Op Http get request
*
* @param url
* @param map
*            Values to request
* @return
*/

static public String get(String url, HashMap<String, String> map) {

int i = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {

Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
if (i == 0) {
url = url + "?" + entry.getKey() + "=" + entry.getValue();
} else {
url = url + "&" + entry.getKey() + "=" + entry.getValue();
}

i++;

}
String reult = post(url, null);
return reult;

}

/**
* Op Http post request , "404error" response if failed
*
* @param url
* @param map
*            Values to request
* @return
*/

static public String post(String url, HashMap<String, String> map) {

DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);

HttpPost post = new HttpPost(url);
Log.i(TAG, url);
post.setHeaders(headers);
String result = "404error";
ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
BasicNameValuePair pair = new BasicNameValuePair(
entry.getKey(), entry.getValue());
pairList.add(pair);
}

}

try {
HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
setCookie(response);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
Log.i(TAG, "result =>" + result);
return result;
}
} catch (ConnectTimeoutException e) {
result = "408timeout";
}

catch (Exception e) {
e.printStackTrace();

}
Log.e(TAG, result);
return result;
}

/**
* Post Bytes to Server
*
* @param url
* @param bytes
*            of text
* @return
*/
public static String PostBytes(String url, byte[] bytes) {
try {
URL murl = new URL(url);
final HttpURLConnection con = (HttpURLConnection) murl
.openConnection();

con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "text/html");
String cookie = headers[10].getValue();
if (!isNull(headers[10].getValue())) {
con.setRequestProperty("cookie", cookie);
}

con.setReadTimeout(TIMEOUT);
con.setConnectTimeout(TIMEOUT);
Log.i(TAG, url);
DataOutputStream dsDataOutputStream = new DataOutputStream(
con.getOutputStream());
dsDataOutputStream.write(bytes, 0, bytes.length);

dsDataOutputStream.close();
if (con.getResponseCode() == HttpStatus.SC_OK) {
InputStream isInputStream = con.getInputStream();
int ch;
StringBuffer buffer = new StringBuffer();
while ((ch = isInputStream.read()) != -1) {
buffer.append((char) ch);
}

Log.i(TAG, "GetDataFromServer>" + buffer.toString());

return buffer.toString();
} else {
return "404error";
}
} catch (SocketTimeoutException e) {
return "timeouterror";
} catch (IOException e) {
// TODO Auto-generated catch block
return "404error";
}
}

/**
* set Cookie
*
* @param response
*/
private static void setCookie(HttpResponse response) {
if (response.getHeaders("Set-Cookie").length > 0) {
Log.d(TAG, response.getHeaders("Set-Cookie")[0].getValue());
headers[10] = new BasicHeader("Cookie",
response.getHeaders("Set-Cookie")[0].getValue());
}
}

/**
* check net work
*
* @param context
* @return
*/
public static boolean hasNetwork(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo workinfo = con.getActiveNetworkInfo();
if (workinfo == null || !workinfo.isAvailable()) {
Toast.makeText(context, "当前无网络连接,请稍后重试", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}

/***
* @category check if the string is null
* @return true if is null
* */
public static boolean isNull(String string) {
boolean t1 = "".equals(string);
boolean t2 = string == null;
boolean t3 = string.equals("null");
if (t1 || t2 || t3) {
return true;
} else {
return false;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: