时间戳以及jsoup应用
以下是测试demo代码,可以下载附件自己测试packagecom.example.androidtest;importjava.io.BufferedInputStream;importjava.io.BufferedReader;importjava.io.ByteArrayOutputStream;importjava.io.DataInputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;importjava.net.URLConnection;importorg.apache.http.HttpResponse;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.util.ByteArrayBuffer;importorg.apache.http.util.EncodingUtils;importorg.jsoup.Jsoup;importorg.jsoup.nodes.Document;importandroid.support.v7.app.ActionBarActivity;importandroid.util.Log;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.webkit.WebView;importandroid.widget.TextView;importandroid.annotation.SuppressLint;importandroid.os.Bundle;publicclassMainActivityextendsActionBarActivityimplementsOnClickListener{privatestaticfinalStringSUDOKU_RANKING_TXT="http://192.168.66.115:8080/sudoku/ranking.txt";URLmyUrl;DataInputStreamdis;Viewmain;privateDocumentdoc;privateTextViewt1;@SuppressLint("NewApi")@OverridepublicvoidonClick(Viewv){inti=main.getSystemUiVisibility();if(i==View.SYSTEM_UI_FLAG_HIDE_NAVIGATION){main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);}elseif(i==View.SYSTEM_UI_FLAG_VISIBLE){main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);}elseif(i==View.SYSTEM_UI_FLAG_LOW_PROFILE){main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);}}@OverrideprotectedvoidonCreate(BundlesavedInstanceState){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();//WebViewbroser=newWebView(this);}privatevoidddd(){//try{//Stringspec="http://www.sina.cn";//myUrl=newURL(spec);//dis=newDataInputStream(myUrl.openStream());//while(dis.readLine()!=null){//StringreadLine=dis.readLine();//System.out.println(readLine);//}////getHtmlString(spec);//dis.close();//}catch(Exceptione){//System.out.println("Error");//}load();//SpannableStringss=newSpannableString("Clickheretobaidu.com");//ss.setSpan(newStyleSpan(Typeface.BOLD),0,6,//Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//ss.setSpan(newURLSpan("http://www.baidu.com"),14,23,//Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//t1.setMovementMethod(LinkMovementMethod.getInstance());}privatevoideee(){newThread(newRunnable(){@Overridepublicvoidrun(){HttpClienthttpClient=newDefaultHttpClient();HttpPostrequest;try{request=newHttpPost(SUDOKU_RANKING_TXT);HttpResponseresponse=httpClient.execute(request);if(response.getStatusLine().getStatusCode()==200){StringBuilderbuilder=newStringBuilder();BufferedReaderreader=newBufferedReader(newInputStreamReader(response.getEntity().getContent()));Stringstr2="";for(Strings=reader.readLine();s!=null;s=reader.readLine()){builder.append(s);}Log.i("TAG","data:"+builder.toString());//从网站获取信息try{StringreadParse=readParse(SUDOKU_RANKING_TXT);Log.e("tag",readParse);URLurl=newURL(SUDOKU_RANKING_TXT);Stringstring=getUrl(url);Log.e("tag",string);}catch(Exceptione){e.printStackTrace();}}}catch(Exceptione){e.printStackTrace();}}}).start();}/***从指定的URL中获取数组**@paramurlPath*@return*@throwsException*/publicstaticStringreadParse(StringurlPath)throwsException{ByteArrayOutputStreamoutStream=newByteArrayOutputStream();byte[]data=newbyte[1024];intlen=0;URLurl=newURL(urlPath);HttpURLConnectionconn=(HttpURLConnection)url.openConnection();InputStreaminStream=conn.getInputStream();while((len=inStream.read(data))!=-1){outStream.write(data,0,len);}inStream.close();returnnewString(outStream.toByteArray());//通过out.Stream.toByteArray获取到写的数据}privateStringgetUrl(URLurl){Stringstr=null;try{URLConnectionuc=url.openConnection();InputStreamis=uc.getInputStream();BufferedInputStreambis=newBufferedInputStream(is);ByteArrayBufferbaf=newByteArrayBuffer(2048);intcun=0;while((cun=bis.read())!=-1){baf.append((byte)cun);}str=EncodingUtils.getString(baf.toByteArray(),"UTF-8");}catch(MalformedURLExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}returnstr;}protectedvoidload(){try{doc=Jsoup.parse(newURL("http://www.sina.cn"),5000);Log.e("load",doc.toString());}catch(MalformedURLExceptione1){e1.printStackTrace();}catch(IOExceptione1){e1.printStackTrace();}}/***@paramurlString*@return*/publicStringgetHtmlString(StringurlString){try{URLurl=null;url=newURL(urlString);URLConnectionucon=null;ucon=url.openConnection();InputStreaminstr=null;instr=ucon.getInputStream();BufferedInputStreambis=newBufferedInputStream(instr);ByteArrayBufferbaf=newByteArrayBuffer(500);intcurrent=0;while((current=bis.read())!=-1){baf.append((byte)current);}returnEncodingUtils.getString(baf.toByteArray(),"gbk");}catch(Exceptione){return"";}}/***jsoup提取src路径,下载网站图片**@authorAdministrator**//**classDownImages{privatestaticintCOUNT=0;privatestaticint*DOWN_COUNT=0;**publicstaticvoidjsoupHTML(StringurlPath)throwsException{Document*doc=Jsoup.connect(urlPath).timeout(1000000).get();//:当前页中的图片Elements*srcLinks=doc.select("img[src$=.jpg]");for(Elementlink:srcLinks){*//:剔除标签,只剩链接路径Stringp_w_picpathsPath=link.attr("src");*System.out.println("当前访问路径:"+p_w_picpathsPath);getImages(p_w_picpathsPath,*"d://p_w_picpaths//0000"+++COUNT+".jpg");}**//:提取网站中所有的href连接Elementslinehrefs=doc.select("a[href]");**for(Elementlinehref:linehrefs){Stringlihr=linehref.attr("href");*if(lihr.length()>4){Stringht=lihr.substring(0,4);Stringhtt=*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();Elementslinks=*docs.select("img[src$=.jpg]");for(Elementlink:links){//*:剔除标签,只剩链接路径Stringp_w_picpathsPath=link.attr("src");*System.out.println("当前访问路径:"+p_w_picpathsPath);getImages(p_w_picpathsPath,*"d://p_w_picpaths//0000"+COUNT+++".jpg");}}}}}*//***@paramurlPath*图片路径*@throwsException*//**publicstaticvoidgetImages(StringurlPath,StringfileName)throws*Exception{URLurl=newURL(urlPath);//:获取的路径//:http协议连接对象*HttpURLConnectionconn=(HttpURLConnection)url.openConnection();*conn.setRequestMethod("GET");conn.setReadTimeout(6*10000);if*(conn.getResponseCode()<10000){InputStreaminputStream=*conn.getInputStream();byte[]data=readStream(inputStream);if*(data.length>(1024*10)){FileOutputStreamoutputStream=new*FileOutputStream(fileName);outputStream.write(data);*System.err.println("第"+++DOWN_COUNT+"图片下载成功");outputStream.close();*}}**}*//***读取url中数据,并以字节的形式返回**@paraminputStream*@return*@throwsException*//**publicstaticbyte[]readStream(InputStreaminputStream)throwsException*{ByteArrayOutputStreamoutputStream=newByteArrayOutputStream();*byte[]buffer=newbyte[1024];intlen=-1;while((len=*inputStream.read(buffer))!=-1){outputStream.write(buffer,0,len);}*outputStream.close();inputStream.close();return*outputStream.toByteArray();}**publicstaticvoidmain(String[]args){try{StringurlPath=*"http://www.22mm.cc/";jsoupHTML(urlPath);}catch(Exceptione){*e.printStackTrace();}finally{System.out.println("共访问"+COUNT+*"张图片,其中下载"+DOWN_COUNT+"张图片");}}}***jsouphttpclient爬取网页并下载google图标**博客分类:javajsouphttpclientjsoup下载地址http://www.jsoup.orghttpclient下载地址*http://hc.apache.org/downloads.cgi其他jar包见附件*//***googlelogo下载程序*//**publicabstractclassCrawler{*//***使用google翻译api**@paramen*@return*//**publicStringtranslateEnToCinese(Stringen){*Translate.setHttpReferrer("http://www.xxx.com");try{return*Translate.execute(en,Language.ENGLISH,Language.CHINESE);}catch*(Exceptione){e.printStackTrace();}return"";}*//***获取一个Map**@return*/finalStringENCORDING="UTF-8";publicbooleanupload(Stringfilepath)throwsException{Stringboundary="---------------------------7db1c523809b2";//+java.util.UUID.randomUUID().toString();////分割线Filefile=newFile(filepath);StringfileName=newString("哈哈嗨".getBytes(),"ISO-8859-1");//用来解析主机名和端口URLurl=newURL("http://192.168.1.120/dev/index.php/Device/UploadFile?filename="+fileName+"&filetype=IMAGE");//用来开启连接StringBuildersb=newStringBuilder();//用来拼装请求/**//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);//打开连接,设置请求头HttpURLConnectionconn=(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);//获取输入输出流OutputStreamout=conn.getOutputStream();FileInputStreamfis=newFileInputStream(file);//将开头部分写出out.write(before);//写出文件数据byte[]buf=newbyte[1024*5];intlen;while((len=fis.read(buf))!=-1)out.write(buf,0,len);//将结尾部分写出out.write(after);InputStreamin=conn.getInputStream();InputStreamReaderisReader=newInputStreamReader(in);BufferedReaderbufReader=newBufferedReader(isReader);Stringline=null;Stringdata="getResult=";while((line=bufReader.readLine())!=null)data+=line;Log.e("fromServer","result="+data);booleansucess=conn.getResponseCode()==200;in.close();fis.close();out.close();conn.disconnect();returnsucess;}/**publicMap<String,Object>getMap(){returnnewHashMap<String,*Object>(0);}*//***下载文件**@paramurl*文件http地址*@paramdir*目标文件*@throwsIOException*//**publicvoiddownloadFile(Stringurl,Stringdir)throwsException{*DefaultHttpClienthttpClient=newDefaultHttpClient();*HttpProtocolParams.setUserAgent(httpClient.getParams(),*"Mozilla/5.0(Windows;U;WindowsNT5.1;zh-CN;rv:1.9.1.9)Gecko/20100315Firefox/3.5.9"*);HttpGethttpGet=newHttpGet();httpGet.setURI(new*java.net.URI(url));**InputStreaminput=null;FileOutputStreamoutput=null;try{*HttpResponseresponse=httpClient.execute(httpGet);HttpEntityentity=*response.getEntity();input=entity.getContent();Filefile=new*File(dir);output=FileUtils.openOutputStream(file);IOUtils.copy(input,*output);}catch(Exceptione){e.printStackTrace();}finally{*IOUtils.closeQuietly(output);IOUtils.closeQuietly(input);}}*//***处理GET请求,返回整个页面**@paramurl*访问地址*@paramparams*编码参数*@return*@throwsException*//**publicsynchronizedStringdoGet(Stringurl,String...params)throws*Exception{DefaultHttpClienthttpClient=newDefaultHttpClient();//*创建httpClient实例HttpProtocolParams.setUserAgent(httpClient.getParams(),*"Mozilla/5.0(Windows;U;WindowsNT5.1;zh-CN;rv:1.9.1.9)Gecko/20100315Firefox/3.5.9"*);Stringcharset="UTF-8";if(null!=params&¶ms.length>=1){*charset=params[0];}HttpGethttpGet=newHttpGet();//创建get方法实例*Stringcontent="";httpGet.setURI(newjava.net.URI(url));try{*HttpResponseresponse=httpClient.execute(httpGet);//执行请求,得到response对象*intresStatu=response.getStatusLine().getStatusCode();//得到返回的状态码if*(resStatu==HttpStatus.SC_OK){//200正常HttpEntityentity=*response.getEntity();//获得相应的实体if(entity!=null){//*使用EntityUtils的toString方法,传递默认编码,在EntityUtils中的默认编码是ISO-8859-1content=*EntityUtils.toString(entity,charset);}}}catch(Exceptione){*System.out.println("访问【"+url+"】出现异常!");e.printStackTrace();}*finally{//关闭资源httpGet.abort();*httpClient.getConnectionManager().shutdown();}returncontent;}}*//***googlelogo下载程序*//**publicclassGoogleLogoCrawlerextendsCrawler{**privatestaticfinalStringURL=*"http://www.logocollect.com/google/year.php?key=%y&page=%p";**privatestaticfinalStringLOGO_URL=*"http://www.logocollect.com/google/";**privatestaticfinalString[]YEARS=newString[]{//"1998","1999",*"2000",//"2001","2002","2003","2004","2005","2006","2007","2008",*"2009","2010","2011","2012"};**privatestaticfinalStringINDEX=*"http://www.logocollect.com/google/year.php?key=%y";**privatestaticfinalStringDIR_PATH="D:\\googlelogos\\";**publicvoiddoStart(){JSONArrayarray=newJSONArray();for(String*year:YEARS){Stringind=INDEX.replaceAll("%y",year);intpageCount*=getPageCount(ind);for(inti=1;i<pageCount+1;i++){Stringurl=*URL.replaceAll("%y",year).replaceAll("%p",i+"");Stringpath=year+*"_"+i;start(url,array,DIR_PATH+path+"\\",path);}}try{*FileUtils.writeStringToFile(newFile(DIR_PATH+"json"),*array.toString(),"UTF-8");}catch(IOExceptione){*e.printStackTrace();}System.out.println(array);}**publicintgetPageCount(Stringurl){intpageCount=1;try{*org.jsoup.nodes.Documentdoc=Jsoup.connect(url).get();**Stringels=doc.html().toString();intstart=els.indexOf("总页数")+4;*Stringtemp=els.substring(start);intend=temp.indexOf(",");*pageCount=Integer.parseInt(els.substring(start,start+end));*System.out.println(pageCount);}catch(IOExceptione){*e.printStackTrace();}returnpageCount;}**publicvoidstart(Stringurl,JSONArrayarray,Stringdir,Stringpath){*try{Stringcontent=super.doGet(url);Documentdoc=*Jsoup.parse(content);Elementsdds=doc.select(".imgimg");*List<Map<String,Object>>list=newArrayList<Map<String,Object>>(0);*for(inti=0;i<dds.size();i++){Elementimg=dds.get(i);String*src=img.select("img").first().attr("src");Stringtitle=*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);}JSONArraytempJsonArray=newJSONArray();for*(Map<String,Object>map:list){JSONObjectjsonObject=new*JSONObject();Stringproxy=*StringUtils.substringAfterLast(map.get("url").toString(),".");long*date=newDate().getTime();Stringname=date+"."+proxy;*jsonObject.put("url",map.get("url").toString());jsonObject.put("dir",*name);jsonObject.put("title",map.get("title").toString());**//翻译//StringdateZh=super.translateEnToCinese(map.get("date")//*.toString());//StringtitleZh=*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(newJSONObject().put(path,*tempJsonArray));}catch(Exceptione){e.printStackTrace();}}**publicstaticvoidmain(String[]args)throwsException{new*GoogleLogoCrawler().doStart();}**}*/}
packagecom.example.androidtest;importandroid.content.Context;importandroid.net.ConnectivityManager;importandroid.net.NetworkInfo;/****工具类,检查当前网络状态**@authorshuimu**/publicclassNetUtil{publicstaticbooleancheckNet(Contextcontext){//获取手机所以连接管理对象(包括wi-fi,net等连接的管理)ConnectivityManagerconn=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);if(conn!=null){//网络管理连接对象NetworkInfoinfo=conn.getActiveNetworkInfo();if(info!=null&&info.isConnected()){//判断当前网络是否连接if(info.getState()==NetworkInfo.State.CONNECTED){returntrue;}}}returnfalse;}}
packagecom.example.androidtest;importjava.sql.Timestamp;importjava.text.SimpleDateFormat;/***时间戳工具类*@authorAdministrator**/publicclassGetTimeUtil{publicstaticStringgetDate(Stringyear,Stringmonth,Stringday){SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");//24小时制java.util.Dated=newjava.util.Date();;Stringstr=sdf.format(d);Stringnowyear=str.substring(0,4);Stringnowmonth=str.substring(5,7);Stringnowday=str.substring(8,10);Stringresult=null;inttemp=Integer.parseInt(nowday)-Integer.parseInt(day);StringBuildersb=newStringBuilder();sb.append(Integer.parseInt(year)+"年");sb.append(Integer.parseInt(month)+"月");sb.append(Integer.parseInt(day)+"日");result=sb.toString();returnresult;}publicstaticStringgetTime(inttimestamp){SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");Stringtime=null;try{java.util.Datecurrentdate=newjava.util.Date();//当前时间longi=(currentdate.getTime()/1000-timestamp)/(60);System.out.println(currentdate.getTime());System.out.println(i);Timestampnow=newTimestamp(System.currentTimeMillis());//获取系统当前时间System.out.println("now-->"+now);//返回结果精确到毫秒。Stringstr=sdf.format(newTimestamp(IntToLong(timestamp)));time=str.substring(11,16);Stringyear=str.substring(0,4);Stringmonth=str.substring(5,7);Stringday=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(Exceptione){e.printStackTrace();}returntime;}//javaTimestamp构造函数需传入Long型publicstaticlongIntToLong(inti){longresult=(long)i;result*=1000;returnresult;}publicstaticvoidmain(String[]args){inttimestamp=1421856000;//假设腾讯微博返回时间戳为秒Stringtime=GetTimeUtil.getTime(timestamp);System.out.println("timestamp-->"+time);//printtimestamp-->7月12日15:59}}
已经上传项目附件
附件:http://down.51cto.com/data/2365513声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。