athrunwang

          紀元
          數據加載中……

          HttpClient 對 cookie 的處理

          public static void main(String[] args) {
                  HttpClient client = new HttpClient();
                  NameValuePair[] nameValuePairs = {
                          new NameValuePair("username", "aaa"),
                          new NameValuePair("passwd", "123456")
                  };
                  PostMethod postMethod = new PostMethod("登錄url");
                  postMethod.setRequestBody(nameValuePairs);
                  int stats = 0;
                  try {
                      stats = client.executeMethod(postMethod);
                  } catch (HttpException e) {
                      e.printStackTrace();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
                  postMethod.releaseConnection();//這里最好把之前的資源放掉
                  CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
                  Cookie[] cookies = cookiespec.match("域名", 80/*端口*/, "/" , false , client.getState().getCookies());
                  for (Cookie cookie : cookies) {
                      System.out.println(cookie.getName() + "##" + cookie.getValue());
                  }
                  
                  HttpMethod method = null;
                  String encode = "utf-8";//頁面編碼,按訪問頁面改動
                  String referer = "http://域名";//http://www.163.com
                  method = new GetMethod("url2");//后續操作
                  method.getParams().setParameter("http.useragent","Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)");
                  method.setRequestHeader("Referer", referer);

                  client.getParams().setContentCharset(encode);
                  client.getParams().setSoTimeout(300000);
                  client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(10, true));
           
                  try {
                      stats = client.executeMethod(method);
                  } catch (HttpException e) {
                      e.printStackTrace();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
                  if (stats == HttpStatus.SC_OK) {
                      System.out.println("提交成功!");
                      
                  }
              }

          posted @ 2011-12-28 20:51 AthrunWang 閱讀(2400) | 評論 (0)編輯 收藏
          jdk7.0 新特性

               摘要: jdk7 增加了一個JLayer,用于在控件上方繪制一個新的圖層。當然jdk6里只要在paint里也能做到,不過新特性方便了很多,最少你可以方便的為Jdk代碼添加這些新特性。public class Diva { public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Run...  閱讀全文

          posted @ 2011-12-28 20:38 AthrunWang 閱讀(221) | 評論 (0)編輯 收藏
          canghailan 使用URLConnection下載文件

          package canghailan;

          import canghailan.util.StopWatch;

          import java.io.*;
          import java.net.URL;
          import java.net.URLConnection;
          import java.util.concurrent.Callable;
          import java.util.concurrent.ExecutionException;
          import java.util.concurrent.ExecutorService;
          import java.util.concurrent.Executors;

          /**
           * User: canghailan
           * Date: 11-12-9
           * Time: 下午2:03
           */
          public class Downloader implements Callable<File> {
              protected int connectTimeout = 30 * 1000; // 連接超時:30s
              protected int readTimeout = 1 * 1000 * 1000; // IO超時:1min

              protected int speedRefreshInterval = 500; // 即時速度刷新最小間隔:500ms

              protected byte[] buffer;

              private URL url;
              private File file;

              private float averageSpeed;
              private float currentSpeed;

              public Downloader() {
                  buffer = new byte[8 * 1024]; // IO緩沖區:8KB
              }

              public void setUrlAndFile(URL url, File file) {
                  this.url = url;
                  this.file = autoRenameIfExist(file);
                  this.averageSpeed = 0;
                  this.currentSpeed = 0;
              }

              public URL getUrl() {
                  return url;
              }

              public File getFile() {
                  return file;
              }

              public float getAverageSpeed() {
                  return averageSpeed;
              }

              public float getCurrentSpeed() {
                  return currentSpeed;
              }

              @Override
              public File call() throws Exception {
                  StopWatch watch = new StopWatch();
                  watch.start();

                  InputStream in = null;
                  OutputStream out = null;
                  try {
                      URLConnection conn = url.openConnection();
                      conn.setConnectTimeout(connectTimeout);
                      conn.setReadTimeout(readTimeout);
                      conn.connect();

                      in = conn.getInputStream();
                      out = new FileOutputStream(file);

                      int time = 0;
                      int bytesInTime = 0;
                      for (; ; ) {
                          watch.split();
                          int bytes = in.read(buffer);
                          if (bytes == -1) {
                              break;
                          }
                          out.write(buffer, 0, bytes);

                          time += watch.getTimeFromSplit();
                          if (time >= speedRefreshInterval) {
                              currentSpeed = getSpeed(bytesInTime, time);
                              time = 0;
                              bytesInTime = 0;
                          }
                      }
                  } catch (IOException e) {
                      file.delete();
                      throw e;
                  } finally {
                      if (in != null) {
                          try {
                              in.close();
                          } catch (IOException e) {
                          }
                      }
                      if (out != null) {
                          try {
                              out.flush();
                              out.close();
                          } catch (IOException e) {
                          }
                      }
                  }

                  watch.stop();
                  averageSpeed = getSpeed(file.length(), watch.getTime());

                  return file;
              }

              private static float getSpeed(long bytesInTime, long time) {
                  return (float) bytesInTime / 1024 / ((float) time / 1000);
              }

              private static String getExtension(String string) {
                  int lastDotIndex = string.lastIndexOf('.');
                  // . ..
                  if (lastDotIndex > 0) {
                      return string.substring(lastDotIndex + 1);
                  } else {
                      return "";
                  }
              }

              private static File autoRenameIfExist(File file) {
                  if (file.exists()) {
                      String path = file.getAbsolutePath();

                      String extension = getExtension(path);
                      int baseLength = path.length();
                      if (extension.length() > 0) {
                          baseLength = path.length() - extension.length() - 1;
                      }

                      StringBuilder buffer = new StringBuilder(path);
                      for (int index = 1; index < Integer.MAX_VALUE; ++index) {
                          buffer.setLength(baseLength);
                          buffer.append('(').append(index).append(')');
                          if (extension.length() > 0) {
                              buffer.append('.').append(extension);
                          }
                          file = new File(buffer.toString());
                          if (!file.exists()) {
                              break;
                          }
                      }

                  }
                  return file;
              }

              public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
                  URL url = new URL("http://www.google.com.hk/");
                  File file = new File("/home/canghailan/google.html");

                  ExecutorService executorService = Executors.newSingleThreadExecutor();
                  Downloader downloader = new Downloader();
                  downloader.setUrlAndFile(url, file);
                  File downloadFIle = executorService.submit(downloader).get();
                  System.out.println("download " + downloadFIle.getName() +
                          " from " + url +
                          " @" + downloader.getAverageSpeed() + "KB/s");
              }
          }
          package canghailan.util;

          import java.util.concurrent.TimeUnit;

          /**
           * User: canghailan
           * Date: 11-12-9
           * Time: 下午3:45
           * <pre>
           * RUNNING:
           * startTime              split                        now
           * |<-   getSplitTime()   ->|<-   getTimeFromSplit()   ->|
           * |<-                   getTime()                     ->|
           * <pre/>
           * <pre>
           * STOPPED:
           * startTime                           stop            now
           * |<-           getTime()            ->|
           * <pre/>
           */
          public class StopWatch {
              private long startTime;
              private long stopTime;

              private State state;
              private boolean split;

              public StopWatch() {
                  reset();
              }

              public void start() {
                  if (state == State.UNSTARTED) {
                      startTime = System.nanoTime();
                      state = State.RUNNING;
                      return;
                  }
                  throw new RuntimeException("Stopwatch already started or stopped.");
              }

              public void stop() {
                  switch (state) {
                      case RUNNING: {
                          stopTime = System.nanoTime();
                      }
                      case SUSPENDED: {
                          state = State.STOPPED;
                          split = false;
                          return;

                      }
                  }
                  throw new RuntimeException("Stopwatch is not running.");
              }

              public void reset() {
                  state = State.UNSTARTED;
                  split = false;
              }

              public void split() {
                  if (state == State.RUNNING) {
                      stopTime = System.nanoTime();
                      split = true;
                      return;
                  }
                  throw new RuntimeException("Stopwatch is not running.");
              }

              public void suspend() {
                  if (state == State.RUNNING) {
                      stopTime = System.nanoTime();
                      state = State.SUSPENDED;
                      return;
                  }
                  throw new RuntimeException("Stopwatch must be running to suspend.");
              }

              public void resume() {
                  if (state == State.SUSPENDED) {
                      startTime += System.nanoTime() - stopTime;
                      state = State.RUNNING;
                      return;
                  }
                  throw new RuntimeException("Stopwatch must be suspended to resume.");
              }

              public long getTime() {
                  return TimeUnit.NANOSECONDS.toMillis(getNanoTime());
              }

              public long getNanoTime() {
                  switch (state) {
                      case RUNNING: {
                          return System.nanoTime() - startTime;
                      }
                      case STOPPED:
                      case SUSPENDED: {
                          return stopTime - startTime;
                      }
                      case UNSTARTED: {
                          return 0;
                      }
                  }
                  throw new RuntimeException("Should never get here.");
              }

              public long getSplitTime() {
                  return TimeUnit.NANOSECONDS.toMillis(getSplitNanoTime());
              }


              public long getSplitNanoTime() {
                  if (split) {
                      return stopTime - startTime;
                  }
                  throw new RuntimeException("Stopwatch must be running and split to get the split time.");
              }

              public long getTimeFromSplit() {
                  return TimeUnit.NANOSECONDS.toMillis(getNanoTimeFromSplit());
              }

              public long getNanoTimeFromSplit() {
                  if (state == State.RUNNING && split) {
                      return System.nanoTime() - stopTime;
                  }
                  throw new RuntimeException("Stopwatch must be running and split to get the time from split.");
              }

              enum State {
                  UNSTARTED,
                  RUNNING,
                  STOPPED,
                  SUSPENDED
              }

          }

          posted @ 2011-12-28 20:07 AthrunWang 閱讀(449) | 評論 (0)編輯 收藏
          java操作excel 插入 讀取 備注 需要smartxls jar包

          import com.smartxls.CommentShape;
          import com.smartxls.WorkBook;

          public class CommentReadSample
          {

              public static void main(String args[])
              {

                  WorkBook workBook = new WorkBook();
                  try
                  {
                      workBook.read("..\\template\\book.xls");

                      // get the first index from the current sheet
                      CommentShape commentShape = workBook.getComment(1, 1);
                      if(commentShape != null)
                      {
                          System.out.println("comment text:" + commentShape.getText());
                          System.out.println("comment author:" + commentShape.getAuthor());
                      }
                  }
                  catch (Exception e)
                  {
                      e.printStackTrace();
                  }
              }
          }

          import com.smartxls.WorkBook;

          public class CommentWriteSample
          {

              public static void main(String args[])
              {
                  WorkBook workBook = new WorkBook();
                  try
                  {
                      //add a comment to B2
                      workBook.addComment(1, 1, "comment text here!", "author name here!");

                      workBook.write(".\\comment.xls");
                  }
                  catch (Exception e)
                  {
                      e.printStackTrace();
                  }
              }
          }

          posted @ 2011-12-28 19:01 AthrunWang 閱讀(720) | 評論 (0)編輯 收藏
          java操作excel 插入 讀取 超鏈接

          import com.smartxls.HyperLink;
          import com.smartxls.WorkBook;

          public class HyperlinkReadSample
          {

              public static void main(String args[])
              {

                  WorkBook workBook = new WorkBook();
                  String version = workBook.getVersionString();
                  System.out.println("Ver:" + version);
                  try
                  {
                      workBook.read("..\\template\\book.xls");

                      // get the first index from the current sheet
                      HyperLink hyperLink = workBook.getHyperlink(0);
                      if(hyperLink != null)
                      {
                          System.out.println(hyperLink.getType());
                          System.out.println(hyperLink.getLinkURLString());
                          System.out.println(hyperLink.getLinkShowString());
                          System.out.println(hyperLink.getToolTipString());
                          System.out.println(hyperLink.getRange());
                      }
                  }
                  catch (Exception e)
                  {
                      e.printStackTrace();
                  }
              }
          }

          import com.smartxls.HyperLink;
          import com.smartxls.WorkBook;

          public class HyperlinkWriteSample
          {

              public static void main(String args[])
              {
                  WorkBook workBook = new WorkBook();
                  try
                  {
                      //add a url link to F6
                      workBook.addHyperlink(5,5,5,5,"http://www.smartxls.com/", HyperLink.kURLAbs,"Hello,web url hyperlink!");

                      //add a file link to F7
                      workBook.addHyperlink(6,5,6,5,"c:\\",HyperLink.kFileAbs,"file link");

                      workBook.write(".\\link.xls");
                  }
                  catch (Exception e)
                  {
                      e.printStackTrace();
                  }
              }
          }

          posted @ 2011-12-28 19:00 AthrunWang 閱讀(957) | 評論 (0)編輯 收藏
          快慢機 java操作excel插入圖片

          import com.smartxls.WorkBook;

          import java.io.FileOutputStream;

          public class ReadImageSample
          {

              public static void main(String args[])
              {
                  try
                  {
                      WorkBook workBook = new WorkBook();

                      //open the workbook
                      workBook.read("..\\template\\book.xls");

                      String filename = "img";
                      int type = workBook.getPictureType(0);
                      if(type == -1)
                          filename += ".gif";
                      else if(type == 5)
                          filename += ".jpg";
                      else if(type == 6)
                          filename += ".png";
                      else if(type == 7)
                          filename += ".bmp";

                      byte[] imagedata = workBook.getPictureData(0);
                      
                      FileOutputStream fos = new FileOutputStream(filename);
                      fos.write(imagedata);
                      fos.close();
                  }
                  catch (Exception e)
                  {
                      e.printStackTrace();
                  }
              }
          }


















          import com.smartxls.PictureShape;
          import com.smartxls.ShapeFormat;
          import com.smartxls.WorkBook;

          public class WriteImagesSample
          {

              public static void main(String args[])
              {
                  try
                  {
                      WorkBook workBook = new WorkBook();

                      //Inserting image
                      PictureShape pictureShape = workBook.addPicture(1, 0, 3, 8, "..\\template\\MS.GIF");
                      ShapeFormat shapeFormat = pictureShape.getFormat();
                      shapeFormat.setPlacementStyle(ShapeFormat.PlacementFreeFloating);
                      pictureShape.setFormat();

                      workBook.write(".\\pic.xls");
                  }
                  catch (Exception e)
                  {
                      e.printStackTrace();
                  }
              }
          }

          posted @ 2011-12-28 19:00 AthrunWang 閱讀(220) | 評論 (0)編輯 收藏
          http短信接口

               摘要: [代碼] [Java]代碼view sourceprint?01package com.sun.duanxin;02import java.io.BufferedReader;03import java.io.IOException;04import java.io.InputStreamReader;05import java.io.U...  閱讀全文

          posted @ 2011-12-26 22:22 AthrunWang 閱讀(214) | 評論 (0)編輯 收藏
          java版的漢字轉拼音程序

               摘要: [文件] ChiToLetter.javaimport java.io.UnsupportedEncodingException;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import java.util.Vector;//實現漢字向拼音的轉化//--------------------...  閱讀全文

          posted @ 2011-12-26 22:17 AthrunWang 閱讀(524) | 評論 (1)編輯 收藏
          Java 生成視頻縮略圖(ffmpeg)

               摘要: [代碼] Java 生成視頻縮略圖(ffmpeg)view sourceprint?01首先下載ffmpeg解壓02 03建立一個bat文件04 05start06 07E:/ffmpeg/bin/ffmpeg.exe -i %1 -ss 20 -vframes 1 -r 1 -ac&nb...  閱讀全文

          posted @ 2011-12-26 22:15 AthrunWang 閱讀(2975) | 評論 (1)編輯 收藏
          主題:Apache與Tomcat搭建集群

               摘要:  早前就解了Apache和Tomcat可以搭建集群,可以負載均衡,升級就不需要停交易,真是強大。昨晚看了google reader的收藏又再次看到這篇文章,于是今天在星巴克研究了一把,發現真的很強大,負載均衡、session復制都可以做到,以后再也不用為升級系統而煩惱了。        下面就來講講是搭建集群的過程,首...  閱讀全文

          posted @ 2011-12-26 22:07 AthrunWang 閱讀(316) | 評論 (0)編輯 收藏
          僅列出標題
          共8頁: 上一頁 1 2 3 4 5 6 7 8 下一頁 
          主站蜘蛛池模板: 安乡县| 屏东市| 辉南县| 广安市| 大邑县| 微山县| 西乌珠穆沁旗| 汶川县| 黄龙县| 涿鹿县| 姜堰市| 乌拉特后旗| 博罗县| 都匀市| 长顺县| 隆林| 隆尧县| 泰州市| 乌鲁木齐市| 苏州市| 马边| 彭山县| 东丰县| 灵台县| 醴陵市| 武清区| 邢台市| 济阳县| 吴堡县| 无棣县| 玉屏| 丹阳市| 潮安县| 双江| 梁山县| 张家界市| 红桥区| 长春市| 磴口县| 彭泽县| 余干县|