整理在学习研究Android开发,编写了一些基本用到的工具集,现在整理分享(后续会持续更新,有问题还请指出)。
1、HttpClient工具,使用Apache的HttpClient类实现get和post方法
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; public class HttpUtil { public static String httpGet(String url) {
String response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (null != httpResponse) {
int status = httpResponse.getStatusLine().getStatusCode();
if (HTTP_OK == status) {
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} else {
response = ("错误码:" + status);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return response;
} public static String httpPost(String url, List<HttpPostParam> params) {
String response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url); if (null != params) {
if (params.size() > 0) {
List<NameValuePair> pairsList = new ArrayList<NameValuePair>();
for (int i = 0; i < params.size(); i++) {
HttpPostParam param = params.get(i);
NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
pairsList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairsList, HTTP.UTF_8));
}
} HttpResponse httpResponse = httpClient.execute(httpPost);
if (null != httpResponse) {
int status = httpResponse.getStatusLine().getStatusCode();
if (HTTP_OK == status) {
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} else {
response = ("错误码:" + status);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} return response;
} private final static int HTTP_OK = 200;
}
post方法自定义了传入的参数结构
public class HttpPostParam { public HttpPostParam() {
} public HttpPostParam(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
} @Override
public String toString() { //转为json格式
return "{key=" + this.key + ",value=" + this.value + "}";
} private String key = null;
private String value = null;
}
2、Json基本操作工具,使用GSON和JAVA中的JSONObject对范型进行操作实现
import java.util.List; import org.json.JSONException;
import org.json.JSONObject; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; public class JsonUtil {
/**
* 对象T转为json字符串
* @param t
* @return json字符串
*/
public static <T> String beanToJson(T t) {
Gson gson = new Gson();
return gson.toJson(t);
} /**
* json字符串转为对象T
* @param json
* @param cls
* @return 对象T
*/
public static <T> T jsonToBean(String json, Class<T> cls) {
Gson gson = new Gson();
return gson.fromJson(json, cls);
} /**
* 对象T列表转为json字符串数组
* @param list
* @returnjson字符串数组
*/
public static <T> String beanlistToJson(List<T> list) {
Gson gson = new Gson();
return gson.toJson(list);
} /**
* json字符串数组转为对象T列表
* @param json
* @param type
* @return 对象T列表
*/
public static <T> List<T> jsonToBeanlist(String json, TypeToken<T> type) {
Gson gson = new Gson();
return gson.fromJson(json, type.getType());
} /**
* json字符串转为json对象
* @param json
* @return json对象
*/
public static JSONObject jsonToObject(String json) {
try {
return new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
} /**
* json对象转为json字符串
* @param object
* @return json字符串
*/
public static String objectToJson(JSONObject object) {
return object.toString();
}
}
3、从网络获取图片资源对象,使用HttpURLConnection实现
/**
* 从网络URL获取图片
* @param imgUrl
* @return 图片对象
*/
public static Bitmap getBitmap(String imgUrl) {
Bitmap bitmap = null;
try {
URL url = new URL(imgUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream iStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(iStream);
iStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
4、将Toast信息放到后台Activity的UI线程中,可实现Toast信息的快速刷新
/**
* 在后台显示前台Toast信息
* @param activity
* @param message
*/
public static void showToast(final Activity activity, final String message) {
activity.runOnUiThread(new Runnable() {
public void run() {
if (null != mToast) {
mToast.cancel();
mToast = null;
}
mToast = Toast.makeText(activity, message, Toast.LENGTH_LONG);
mToast.show();
}
});
} private static Toast mToast = null;
5、XML信息解析,使用DOM和SAX实现
DOM实现:
import java.io.File;
import java.io.InputStream;
import java.util.List; public class DOMParseInstance {
public static List<Object> parse(InputStream iStream) {
return new DOMHandler().parse(iStream);
} public static List<Object> parse(File file) {
return new DOMHandler().parse(file);
} public static List<Object> parse(String xml) {
return new DOMHandler().parse(xml);
}
}
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList; public class DOMHandler {
public List<Object> parse(InputStream iStream) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(iStream);
return parseDocument(document);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public List<Object> parse(File file) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
return parseDocument(document);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public List<Object> parse(String xml) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xml);
return parseDocument(document);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} private List<Object> parseDocument(Document document) {
if (null == document) {
return null;
} //注意这里的数据类型,需要修改
List<Object> xmlList = new ArrayList<>();
Element rootElement = document.getDocumentElement(); //根节点
if (rootElement.hasChildNodes()) { //存在子节点
NodeList nodeList = rootElement.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) { //遍历子节点
//由于XML是标准格式的XML,DOM在解析时会将/n /t当做一个节点
//判断当前NodeList中的子项是否为Element对象实例,否则强制类型转换就异常
if (nodeList.item(i) instanceof Element) {
Element node = (Element)nodeList.item(i);
if (null != node) { //获取到一个节点,判断节点的名称是否为需要的节点名称 //如果有子节点,可以继续遍历子节点
//遍历节点Person下的所有子节点
NodeList childList = node.getChildNodes();
for (int j = 0; j < childList.getLength(); j++) {
Node childNode = childList.item(j);
if (null != childNode) {
if (Node.ELEMENT_NODE == childNode.getNodeType()) { //判断是否为节点
//子节点信息
}
}
}
}
}
}
} return xmlList;
}
}
SAX实现:
import java.io.File;
import java.io.IOException;
import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; public class SAXParseInstance { public static void prase(String xml, DefaultHandler handler) {
try {
getInstance().parse(xml, handler);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} public static void prase(InputStream iStream, DefaultHandler handler) {
try {
getInstance().parse(iStream, handler);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} public static void prase(File file, DefaultHandler handler) {
try {
getInstance().parse(file, handler);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} private static SAXParser getInstance() {
try {
return SAXParserFactory.newInstance().newSAXParser();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
}
import java.util.ArrayList;
import java.util.List; import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; public class SAXHandler extends DefaultHandler{ public List<Object> getXmList() {
return xmlList;
} @Override
public void startDocument() throws SAXException {
//申请xml数据列表内存
xmlList = new ArrayList<>(); super.startDocument();
} @Override
public void endDocument() throws SAXException {
//结束,可以做一些尾部处理 super.endDocument();
} @Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
//进入一个子节点,可以根据qName判断是那个节点,在这里可以申请子节点的内存信息 tagName = qName;
super.startElement(uri, localName, qName, attributes);
} @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
//根据uri判断是那个前缀,qName判断是那个节点,将解析的数据放入列表 tagName = null;
super.endElement(uri, localName, qName);
} @Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (null != tagName) { //有子节点
String data = new String(ch, start, length); //节点的数据
//根据tagName的节点判断是那个节点信息,然后获取对应类型的数据 }
super.characters(ch, start, length);
} private String tagName = null; //标记当前节点
//这里的数据类型需要修改
private List<Object> xmlList = null; //xml信息列表
}
6、Android内部与SD卡一些操作
import java.io.File;
import java.text.DecimalFormat; import android.os.Environment; public class Utils {
/**
* 获取内部存储路径
* @return 路径
*/
public static String getInnerSDCardPath() {
return Environment.getExternalStorageDirectory().getPath();
} /**
* 获取SD卡存储路径
* @return 路径
*/
public static String getExtSDCardPath() {
File dir = null;
if (getSDCardEnable()) {
dir = Environment.getExternalStorageDirectory();//获取跟目录
}
return dir.toString();
} /**
* SD卡是否可用
* @return
*/
public static boolean getSDCardEnable() {
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
} /**
* 创建目录
* @param path
*/
public static void makeDirs(String path) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
} /**
* 字节大小转换
* @param value
* @return
*/
public static String convertByte(String value) {
String strRet = null;
Float fValue = Float.valueOf(value);
float fByte = fValue.floatValue(); DecimalFormat decimalFormat = new DecimalFormat(".0"); //精确度为小数点后1位
if (fByte >= G_NUM) {
strRet = decimalFormat.format(fByte/G_NUM) + "GB";
} else if (fByte >= M_NUM) {
strRet = decimalFormat.format(fByte/M_NUM) + "MB";
} else if (fByte >= K_NUM) {
strRet = decimalFormat.format(fByte/K_NUM) + "KB";
} else if (fByte >= B_NUM) {
strRet = decimalFormat.format(fByte/B_NUM) + "B";
} return strRet;
} private static final long B_NUM = 1024;
private static final long K_NUM = B_NUM * 1024;
private static final long M_NUM = K_NUM * 1024;
private static final long G_NUM = M_NUM * 1024;
}