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("提交成功!");
}
}
摘要: jdk7 增加了一个JLayer,用于在控件上方绘制一个新的图层。当然jdk6里只要在paint里也能做到,不过新特性方便了很多,最少你可以方便的为Jdk代码添加这些新特性。public class Diva { public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Run... 阅读全文
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
}
}
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();
}
}
}
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();
}
}
}
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();
}
}
}
摘要: [代码] [Java]代码view sourceprint?01package com.sun.duanxin;02import java.io.BufferedReader;03import java.io.IOException;04import java.io.InputStreamReader;05import java.io.U... 阅读全文
摘要: [文件] ChiToLetter.javaimport java.io.UnsupportedEncodingException;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import java.util.Vector;//实现汉字向拼音的转化//--------------------... 阅读全文
摘要: [代码] 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... 阅读全文
摘要: 早前就解了Apache和Tomcat可以搭建集群,可以负载均衡,升级就不需要停交易,真是强大。昨晚看了google reader的收藏又再次看到这篇文章,于是今天在星巴克研究了一把,发现真的很强大,负载均衡、session复制都可以做到,以后再也不用为升级系统而烦恼了。 下面就来讲讲是搭建集群的过程,首... 阅读全文