иллюстрировать
Этот пример может отслеживать кнопку Snap-Up Juhuasuan и автоматически всплыть на страницу, когда наступает время сбора полной точки Juhuasuan (URL определяется самим собой).
Вы можете настроить мониторинг последних нескольких минут, а также ускорить скорость обновления за счет многопоточного чтения.
Исходный код
пакет com.itechzero.pricemonitor; Импорт java.io.bufferedinputstream; Импорт java.io.bufferedReader; Импорт java.io.inputStreamReader; Импорт java.io.inputStreamReader; импортировать java.io.outputstreamwriter; Импорт java.net.uri; импортировать java.net.url; Импорт java.net.urlconnection; импортировать java.text.simpledateformat; импортировать java.util.date; / ** * pricemonitor.java * * @author techzero * @email [email protected] * @time 2014-5-21 1:24:30 */ класс mythread extends extends {public void run () {try {// Параметр здесь является количество минут мониторинга PRICemonitor.MonitorButton (10); } catch (Exception e) {e.printstackTrace (); }}}}; открытый класс PRICemonitor {// URL с контролируемым продуктом Private Static String url = "http://detail.ju.taobao.com/home.htm?spm=608.2214381.3.1.adpejn&item_id=38260927591&id=100002781939"; // кнопка мониторинга Public Static void monitorbutton (int lastminute) {int nowminute = integer.parseint (new SimpleDateFormat ("MM"). Format (new Date ())); int endminute = integer.parseint (new SimpleDateFormat ("MM"). Format (new Date ())) + LastMinute; while (nowminute <endminute) {nowminute = integer.parseint (new SimpleDateFormat ("MM"). Format (new Date ())); String result [] = getCurrentButtonandForm (url, "GB2312"). Split (","); // текущая кнопка Status String CurrentButton = Result [0]; // сразу же захватить форму // строка = результат [1]; String nowtime = new SimpleDateFormat ("yyyy-mm-dd hh: mm: ss"). Format (new date ()); System.out.println (сейчас время + » - теперь кнопка« + currentbutton); if (currentButton == "Get now" || currentButton.equals ("Get now") || currentbutton == "Get stow" || currentButton.equals ("Get styal")) {System.out.println ("Get now!"); try {java.awt.desktop.getdesktop (). Обзор (new uri (url)); } catch (Exception e) {e.printstackTrace (); } // dopost (form); перерыв; } else if (currentButton == "Swed Out" || currentButton.equals ("sed Out") || currentbutton.equals ("inded") || currentbutton.equals ("inded")) {System.out.println ("попробуйте еще раз!"); перерыв; } else {System.out.println ("еще не начался, подожди!"); }}} // Получить текущую кнопку Состояния общедоступной статической строки getCurrentButtonAndform (string url, string encoding) {if (url == null || "" .equals (url.trim ())) return null; String buttonstate = ""; StringBuffer Content = new StringBuffer (); логический Formflag = false; try {// Создать новый URL -объект URL U = новый URL (URL); InputStream IS = новый BufferedInputStream (u.OpenStream ()); InputStreamReader thehtml = new InputStreamReader (IS, кодирование! = NULL? Кодирование: "GB2312"); BufferedReader BR = новый BufferedReader (TheHTML); Строка s = ""; while ((s = br.readline ())! = null) {if (s.indexof ("<input type =/" class =/"buyAction j_buysubmit/" title =/"grab/" value =/"grab/"/> ")! = -1) {buttonstate =" Grab/"; } else if (s.indexof ("<a href =/"#/"class =/" дополнительное уведомление j_buybuttonsub/"> Напоминание о открытии команды </a>")! = -1) {buttonstate = "Открытие команды" напоминание "; } else if (s.indexof ("<div class = /" main -box chance /">")! = -1) {buttonstate = "sed Out"; } else if (s.indexof ("<span class =/" out floatright/"> распродан ... </span>")! = -1) {buttonstate = "sed Out"; } else if (s.indexof ("<span class =/" out floatright/"> ended ... </span>")! = -1) {buttonstate = "ended"; } if (s.indexof ("<form class =/" j_buysubform/"data-ccb =/" 0/"data-ques =/" 0/"action")! = -1) {content.append (s + "/r/n"); formflag = true; } if (formflag == true) {if (s.indexof ("<input name =/'_ tb_token_/' type =/'hidden/' value")! = -1) {content.append (s + "/r/n"); } if (s.indexof ("<input type =/" hidden/"name =/" _ input_charset/"value")! = -1) {content.append (s + "/r/n"); } if (s.indexof ("<input type =/" hidden/"name =/" itemid/"value")! = -1) {content.append (s + "/r/n"); } if (s.indexof ("<input type =/" hidden/"name =/" id/"value")! = -1) {content.append (s + "/r/n"); } if (s.indexof ("<input type =/" hidden/"name =/" id/"value")! = -1) {content.append (s + "/r/n"); } if (s.indexof ("<input type =/" hidden/"name =/" tgtype/"value")! = -1) {content.append (s + "/r/n"); } if (s.indexof ("<input type =/" upper/"class =/" buyAction j_buysubmit/"")! = -1) {content.append (s + "/r/n"); } if (s.indexof ("<div class =/" time -banner/">")! = -1) {content.append (s + "/r/n"); }} if (s.indexof ("<div class =/" time -banner/">")! = -1) {break; }} br.close (); } catch (Exception e) {System.err.println (e); вернуть "Ошибка открытия URL"; } return Buttonstate + "," + content; } // Отправить форму public Static String Dopost (String form) {StringBuffer content = new StringBuffer (); try {urlconnection connection = new URL (url) .openconcenection (); connection.setDoOutput (true); OutputStreamWriter OS = новый outputStreamWriter (connection.getOutputStream (), "UTF-8"); OS.Write (форма); os.flush (); os.close (); Inputstream is = connection.getInputStream (); InputStreamReader theHtml = new InputStreamReader (IS); BufferedReader BR = новый BufferedReader (TheHTML); Строка s = ""; while ((s = br.readline ())! = null) {content.append (s + "/r/n"); }} catch (Exception e) {e.printstackTrace (); } // возвращает контент страницы, возвращаемый после отправки формы return content.tostring (); } // Log in public static void doLogin(String username, String password) { String form = "<form id=/"J_StaticForm/" action=/"https://login.taobao.com/member/login.jhtml/" method=/"post/" autocomplete=/"on/"><input type=/"text/" name=/"TPL_username/" id =/"tpl_username_1/" value =/"" + username + "/"> <input type =/"password/" name =/"tpl_password/" id =/"tpl_password_1/" value =/"" + password + "/"> <input type =/"hidden/" id =/"j_tpl_redirect_urect_urect_urect_urect_urect_rect_rece_rece_rece_rece_rece_rece_rece_rece_rece_rece_rece_rece_rece_rece_rece_rece_rect_rece_rece_rece_rect_rece_rece_recemect ="/" value =/"http://www.taobao.com/?spm=a2107.1.1000340.1.al2mpn/"> <button type =/"Отправить/" id =/"j_submitstatic/"> login </button> </form> "; Dopost (форма); } public static void main (string [] args) {// dologin (); // new Mythread (). start (); // new Mythread (). start (); // new Mythread (). start (); // new Mythread (). start (); // new Mythread (). start (); }}
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.