時間戳以及jsoup應用

以下是測試demo代碼,可以下載附件自己測試
package com.example.androidtest;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity implements OnClickListener {

	private static final String SUDOKU_RANKING_TXT = "http://192.168.66.115:8080/sudoku/ranking.txt";
	URL myUrl;
	DataInputStream dis;
	View main;
	private Document doc;
	private TextView t1;

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		int i = main.getSystemUiVisibility();
		if (i == View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) {
			main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
		} else if (i == View.SYSTEM_UI_FLAG_VISIBLE) {
			main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
		} else if (i == View.SYSTEM_UI_FLAG_LOW_PROFILE) {
			main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		main = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
		// main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
		// main.setOnClickListener(this);
		setContentView(main);
		t1 = (TextView) findViewById(R.id.t1);
		eee();
//		WebView broser = new WebView(this);
	}

	private void ddd() {
		// try {
		// String spec = "http://www.sina.cn";
		// myUrl = new URL(spec);
		// dis = new DataInputStream(myUrl.openStream());
		// while (dis.readLine() != null) {
		// String readLine = dis.readLine();
		// System.out.println(readLine);
		// }
		// // getHtmlString(spec);
		// dis.close();
		// } catch (Exception e) {
		// System.out.println("Error");
		// }
		load();
		// SpannableString ss = new SpannableString("Click here to baidu.com");
		// ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 6,
		// Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		// ss.setSpan(new URLSpan("http://www.baidu.com"), 14, 23,
		// Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		// t1.setMovementMethod(LinkMovementMethod.getInstance());
	}

	private void eee() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost request;
				try {
					request = new HttpPost(SUDOKU_RANKING_TXT);
					HttpResponse response = httpClient.execute(request);
					if (response.getStatusLine().getStatusCode() == 200) {
						StringBuilder builder = new StringBuilder();
						BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						String str2 = "";
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							builder.append(s);
						}
						Log.i("TAG", "data :" + builder.toString());
						// 從網站獲取信息
						try {
							String readParse = readParse(SUDOKU_RANKING_TXT);
							Log.e("tag", readParse);
							URL url = new URL(SUDOKU_RANKING_TXT);
							String string = getUrl(url);
							Log.e("tag", string);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}).start();
	}

	/**
	 * 從指定的URL中獲取數組
	 * 
	 * @param urlPath
	 * @return
	 * @throws Exception
	 */
	public static String readParse(String urlPath) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		URL url = new URL(urlPath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		InputStream inStream = conn.getInputStream();
		while ((len = inStream.read(data)) != -1) {
			outStream.write(data, 0, len);
		}
		inStream.close();
		return new String(outStream.toByteArray());// 通過out.Stream.toByteArray獲取到寫的數據
	}

	private String getUrl(URL url) {
		String str = null;
		try {
			URLConnection uc = url.openConnection();
			InputStream is = uc.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer baf = new ByteArrayBuffer(2048);
			int cun = 0;
			while ((cun = bis.read()) != -1) {
				baf.append((byte) cun);
			}
			str = EncodingUtils.getString(baf.toByteArray(), "UTF-8");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}

	protected void load() {
		try {
			doc = Jsoup.parse(new URL("http://www.sina.cn"), 5000);
			Log.e("load", doc.toString());
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * @param urlString
	 * @return
	 */
	public String getHtmlString(String urlString) {
		try {
			URL url = null;
			url = new URL(urlString);

			URLConnection ucon = null;
			ucon = url.openConnection();

			InputStream instr = null;
			instr = ucon.getInputStream();

			BufferedInputStream bis = new BufferedInputStream(instr);

			ByteArrayBuffer baf = new ByteArrayBuffer(500);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}
			return EncodingUtils.getString(baf.toByteArray(), "gbk");
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * jsoup提取src路徑,下載網站圖片
	 * 
	 * @author Administrator
	 * 
	 */
	/*
	 * class DownImages { private static int COUNT = 0; private static int
	 * DOWN_COUNT = 0;
	 * 
	 * public static void jsoupHTML(String urlPath) throws Exception { Document
	 * doc = Jsoup.connect(urlPath).timeout(1000000).get(); // :當前頁中的圖片 Elements
	 * srcLinks = doc.select("img[src$=.jpg]"); for (Element link : srcLinks) {
	 * // :剔除標籤,只剩鏈接路徑 String imagesPath = link.attr("src");
	 * System.out.println("當前訪問路徑:" + imagesPath); getImages(imagesPath,
	 * "d://images//0000" + ++COUNT + ".jpg"); }
	 * 
	 * // :提取網站中所有的href連接 Elements linehrefs = doc.select("a[href]");
	 * 
	 * for (Element linehref : linehrefs) { String lihr = linehref.attr("href");
	 * if (lihr.length() > 4) { String ht = lihr.substring(0, 4); String htt =
	 * lihr.substring(0, 1); if (!ht.equals("http") && htt.equals("/")) { lihr =
	 * urlPath + lihr; } if (lihr.substring(0, 4).equals("http")) { Document
	 * docs = Jsoup.connect(lihr).timeout(1000000).get(); Elements links =
	 * docs.select("img[src$=.jpg]"); for (Element link : links) { //
	 * :剔除標籤,只剩鏈接路徑 String imagesPath = link.attr("src");
	 * System.out.println("當前訪問路徑:" + imagesPath); getImages(imagesPath,
	 * "d://images//0000" + COUNT++ + ".jpg"); } } } } }
	 *//**
	 * @param urlPath
	 *            圖片路徑
	 * @throws Exception
	 */
	/*
	 * public static void getImages(String urlPath, String fileName) throws
	 * Exception { URL url = new URL(urlPath);// :獲取的路徑 // :http協議連接對象
	 * HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	 * conn.setRequestMethod("GET"); conn.setReadTimeout(6 * 10000); if
	 * (conn.getResponseCode() < 10000) { InputStream inputStream =
	 * conn.getInputStream(); byte[] data = readStream(inputStream); if
	 * (data.length > (1024 * 10)) { FileOutputStream outputStream = new
	 * FileOutputStream(fileName); outputStream.write(data);
	 * System.err.println("第" + ++DOWN_COUNT + "圖片下載成功"); outputStream.close();
	 * } }
	 * 
	 * }
	 *//**
	 * 讀取url中數據,並以字節的形式返回
	 * 
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
	/*
	 * public static byte[] readStream(InputStream inputStream) throws Exception
	 * { ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	 * byte[] buffer = new byte[1024]; int len = -1; while ((len =
	 * inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); }
	 * outputStream.close(); inputStream.close(); return
	 * outputStream.toByteArray(); }
	 * 
	 * public static void main(String[] args) { try { String urlPath =
	 * "http://www.22mm.cc/"; jsoupHTML(urlPath); } catch (Exception e) {
	 * e.printStackTrace(); } finally { System.out.println("共訪問" + COUNT +
	 * "張圖片,其中下載" + DOWN_COUNT + "張圖片"); } } }
	 * 
	 * 
	 * jsoup httpclient 爬取網頁並下載google圖標
	 * 
	 * 博客分類: java jsouphttpclient jsoup下載地址 http://www.jsoup.org httpclient下載地址
	 * http://hc.apache.org/downloads.cgi 其他jar包見附件
	 *//**
	 * google logo 下載程序
	 */
	/*
	 * public abstract class Crawler {
	 *//**
	 * 使用google 翻譯api
	 * 
	 * @param en
	 * @return
	 */
	/*
	 * public String translateEnToCinese(String en) {
	 * Translate.setHttpReferrer("http://www.xxx.com"); try { return
	 * Translate.execute(en, Language.ENGLISH, Language.CHINESE); } catch
	 * (Exception e) { e.printStackTrace(); } return ""; }
	 *//**
	 * 獲取一個Map
	 * 
	 * @return
	 */
	final String ENCORDING = "UTF-8";

	public boolean upload(String filepath) throws Exception {
		String boundary = "---------------------------7db1c523809b2";// +java.util.UUID.randomUUID().toString();//
		// 分割線
		File file = new File(filepath);

		String fileName = new String("哈哈嗨".getBytes(), "ISO-8859-1");
		// 用來解析主機名和端口
		URL url = new URL("http://192.168.1.120/dev/index.php/Device/UploadFile?filename=" + fileName + "&filetype=IMAGE");
		// 用來開啓連接
		StringBuilder sb = new StringBuilder();
		// 用來拼裝請求

		/*
		 * // username字段 sb.append("--" + boundary + "\r\n");
		 * sb.append("Content-Disposition: form-data; name=\"username\"" +
		 * "\r\n"); sb.append("\r\n"); sb.append(username + "\r\n");
		 * 
		 * // password字段 sb.append("--" + boundary + "\r\n");
		 * sb.append("Content-Disposition: form-data; name=\"password\"" +
		 * "\r\n"); sb.append("\r\n"); sb.append(password + "\r\n");
		 */

		// 文件部分
		sb.append("--" + boundary + "\r\n");
		sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filepath + "\"" + "\r\n");
		sb.append("Content-Type: application/octet-stream" + "\r\n");
		sb.append("\r\n");

		// 將開頭和結尾部分轉爲字節數組,因爲設置Content-Type時長度是字節長度
		byte[] before = sb.toString().getBytes(ENCORDING);
		byte[] after = ("\r\n--" + boundary + "--\r\n").getBytes(ENCORDING);

		// 打開連接, 設置請求頭
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(10000);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
		conn.setRequestProperty("Content-Length", before.length + file.length() + after.length + "");

		conn.setDoOutput(true);
		conn.setDoInput(true);

		// 獲取輸入輸出流
		OutputStream out = conn.getOutputStream();
		FileInputStream fis = new FileInputStream(file);
		// 將開頭部分寫出
		out.write(before);

		// 寫出文件數據
		byte[] buf = new byte[1024 * 5];
		int len;
		while ((len = fis.read(buf)) != -1)
			out.write(buf, 0, len);

		// 將結尾部分寫出
		out.write(after);

		InputStream in = conn.getInputStream();
		InputStreamReader isReader = new InputStreamReader(in);
		BufferedReader bufReader = new BufferedReader(isReader);
		String line = null;
		String data = "getResult=";
		while ((line = bufReader.readLine()) != null)
			data += line;
		Log.e("fromServer", "result=" + data);
		boolean sucess = conn.getResponseCode() == 200;
		in.close();
		fis.close();
		out.close();
		conn.disconnect();

		return sucess;
	}

	/*
	 * public Map<String, Object> getMap() { return new HashMap<String,
	 * Object>(0); }
	 *//**
	 * 下載文件
	 * 
	 * @param url
	 *            文件http地址
	 * @param dir
	 *            目標文件
	 * @throws IOException
	 */
	/*
	 * public void downloadFile(String url, String dir) throws Exception {
	 * DefaultHttpClient httpClient = new DefaultHttpClient();
	 * HttpProtocolParams.setUserAgent(httpClient.getParams(),
	 * "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9"
	 * ); HttpGet httpGet = new HttpGet(); httpGet.setURI(new
	 * java.net.URI(url));
	 * 
	 * InputStream input = null; FileOutputStream output = null; try {
	 * HttpResponse response = httpClient.execute(httpGet); HttpEntity entity =
	 * response.getEntity(); input = entity.getContent(); File file = new
	 * File(dir); output = FileUtils.openOutputStream(file); IOUtils.copy(input,
	 * output); } catch (Exception e){ e.printStackTrace(); } finally {
	 * IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
	 */

	/**
	 * 處理GET請求,返回整個頁面
	 * 
	 * @param url
	 *            訪問地址
	 * @param params
	 *            編碼參數
	 * @return
	 * @throws Exception
	 */
	/*
	 * public synchronized String doGet(String url, String... params) throws
	 * Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); //
	 * 創建httpClient實例 HttpProtocolParams.setUserAgent(httpClient.getParams(),
	 * "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9"
	 * ); String charset = "UTF-8"; if (null != params && params.length >= 1) {
	 * charset = params[0]; } HttpGet httpGet = new HttpGet(); // 創建get方法實例
	 * String content = ""; httpGet.setURI(new java.net.URI(url)); try {
	 * HttpResponse response = httpClient.execute(httpGet); // 執行請求,得到response對象
	 * int resStatu = response.getStatusLine().getStatusCode(); // 得到返回的狀態碼 if
	 * (resStatu == HttpStatus.SC_OK) { // 200正常 HttpEntity entity =
	 * response.getEntity(); // 獲得相應的實體 if (entity != null) { //
	 * 使用EntityUtils的toString方法,傳遞默認編碼,在EntityUtils中的默認編碼是ISO-8859-1 content =
	 * EntityUtils.toString(entity, charset); } } } catch (Exception e) {
	 * System.out.println("訪問【" + url + "】出現異常!"); e.printStackTrace(); }
	 * finally { // 關閉資源 httpGet.abort();
	 * httpClient.getConnectionManager().shutdown(); } return content; } }
	 *//**
	 * google logo 下載程序
	 */
	/*
	 * public class GoogleLogoCrawler extends Crawler {
	 * 
	 * private static final String URL =
	 * "http://www.logocollect.com/google/year.php?key=%y&page=%p";
	 * 
	 * private static final String LOGO_URL =
	 * "http://www.logocollect.com/google/";
	 * 
	 * private static final String[] YEARS = new String[] { //"1998", "1999",
	 * "2000", //"2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008",
	 * "2009", "2010", "2011", "2012" };
	 * 
	 * private static final String INDEX =
	 * "http://www.logocollect.com/google/year.php?key=%y";
	 * 
	 * private static final String DIR_PATH = "D:\\googlelogos\\";
	 * 
	 * public void doStart() { JSONArray array = new JSONArray(); for (String
	 * year : YEARS) { String ind = INDEX.replaceAll("%y", year); int pageCount
	 * = getPageCount(ind); for (int i = 1; i < pageCount+1; i++) { String url =
	 * URL.replaceAll("%y", year).replaceAll("%p", i + ""); String path = year +
	 * "_" + i; start(url, array, DIR_PATH + path + "\\", path); } } try {
	 * FileUtils.writeStringToFile(new File(DIR_PATH + "json"),
	 * array.toString(), "UTF-8"); } catch (IOException e) {
	 * e.printStackTrace(); } System.out.println(array); }
	 * 
	 * public int getPageCount(String url) { int pageCount = 1; try {
	 * org.jsoup.nodes.Document doc = Jsoup.connect(url).get();
	 * 
	 * String els = doc.html().toString(); int start = els.indexOf("總頁數") + 4;
	 * String temp = els.substring(start); int end = temp.indexOf(",");
	 * pageCount = Integer.parseInt(els.substring(start,start+end));
	 * System.out.println(pageCount); } catch (IOException e) {
	 * e.printStackTrace(); } return pageCount; }
	 * 
	 * public void start(String url, JSONArray array, String dir, String path) {
	 * try { String content = super.doGet(url); Document doc =
	 * Jsoup.parse(content); Elements dds = doc.select(".img img");
	 * List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(0);
	 * for (int i = 0; i < dds.size(); i++) { Element img = dds.get(i); String
	 * src = img.select("img").first().attr("src"); String title =
	 * img.select("img").first().attr("title"); Map<String, Object> map =
	 * super.getMap();
	 * 
	 * map.put("url", LOGO_URL + src); map.put("title", title);
	 * 
	 * list.add(map); } JSONArray tempJsonArray = new JSONArray(); for
	 * (Map<String, Object> map : list) { JSONObject jsonObject = new
	 * JSONObject(); String proxy =
	 * StringUtils.substringAfterLast(map.get("url") .toString(), "."); long
	 * date = new Date().getTime(); String name = date + "." + proxy;
	 * jsonObject.put("url", map.get("url").toString()); jsonObject.put("dir",
	 * name); jsonObject.put("title", map.get("title").toString());
	 * 
	 * // 翻譯 // String dateZh = super.translateEnToCinese(map.get("date") //
	 * .toString()); // String titleZh =
	 * super.translateEnToCinese(map.get("title") // .toString()); //
	 * json.put("title_zh_cn", dateZh + " - " + titleZh);
	 * 
	 * // 下載圖片 super.downloadFile(map.get("url").toString(), dir + name);
	 * tempJsonArray.put(jsonObject); } array.put(new JSONObject().put(path,
	 * tempJsonArray)); } catch (Exception e) { e.printStackTrace(); } }
	 * 
	 * public static void main(String[] args) throws Exception { new
	 * GoogleLogoCrawler().doStart(); }
	 * 
	 * }
	 */
}
package com.example.androidtest;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/***
 * 工具類,檢查當前網絡狀態
 * 
 * @author shuimu
 * 
 */
public class NetUtil {

	public static boolean checkNet(Context context) {

		// 獲取手機所以連接管理對象(包括wi-fi,net等連接的管理)

		ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conn != null) {
			// 網絡管理連接對象
			NetworkInfo info = conn.getActiveNetworkInfo();

			if (info != null && info.isConnected()) {
				// 判斷當前網絡是否連接
				if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}

		}

		return false;
	}
}
package com.example.androidtest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
/**
 * 時間戳工具類
 * @author Administrator
 *
 */
public class GetTimeUtil {

	public static String getDate(String year, String month, String day) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小時制
		java.util.Date d = new java.util.Date();
		;
		String str = sdf.format(d);
		String nowyear = str.substring(0, 4);
		String nowmonth = str.substring(5, 7);
		String nowday = str.substring(8, 10);
		String result = null;

		int temp = Integer.parseInt(nowday) - Integer.parseInt(day);
		StringBuilder sb = new StringBuilder();
		sb.append(Integer.parseInt(year) + "年");
		sb.append(Integer.parseInt(month) + "月");
		sb.append(Integer.parseInt(day) + "日");
		result = sb.toString();
		return result;
	}

	public static String getTime(int timestamp) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = null;
		try {
			java.util.Date currentdate = new java.util.Date();// 當前時間

			long i = (currentdate.getTime() / 1000 - timestamp) / (60);
			System.out.println(currentdate.getTime());
			System.out.println(i);
			Timestamp now = new Timestamp(System.currentTimeMillis());// 獲取系統當前時間
			System.out.println("now-->" + now);// 返回結果精確到毫秒。

			String str = sdf.format(new Timestamp(IntToLong(timestamp)));
			time = str.substring(11, 16);

			String year = str.substring(0, 4);
			String month = str.substring(5, 7);
			String day = str.substring(8, 10);
			System.out.println(str);
			System.out.println(time);
			System.out.println(getDate(year, month, day));
			time = getDate(year,month, day);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return time;
	}

	// java Timestamp構造函數需傳入Long型
	public static long IntToLong(int i) {
		long result = (long) i;
		result *= 1000;
		return result;
	}

	public static void main(String[] args) {
		int timestamp = 1421856000; // 假設騰訊微博返回時間戳爲秒
		String time = GetTimeUtil.getTime(timestamp);
		System.out.println("timestamp-->" + time);
		// print timestamp-->7月12日15:59
	}

}

已經上傳項目附件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章